Search code examples
pythondatetimedeserialization

Converting a datetime into a string and back again


I have a datetime that I save to a file like this:

time1 = datetime.datetime.now()
f.write(str(time1))

Now when I read it I realize time is a string. I've tried different ways to convert it but with no luck so far.

time = line[x:x+26]

How can I convert a string representation of a datetime back into a datetime object?


Solution

  • First, you need to figure out the format of the date in your file and use the strptime method, e.g.

    # substitute your format
    # the one below is likely to be what's saved by str(datetime)
    previousTime = datetime.datetime.strptime(line[x:x+26], "%Y-%m-%d %H:%M:%S.%f") 
    

    (You'd better use dt.strftime(...) than str(dt) though)

    Then subtract the datetime objects to get a timedelta

    delta = datetime.datetime.now() - previousTime