Converting a datetime into a string and back again
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
It's a little simpler in python 3.7+
To string:
import datetime
my_date_string = datetime.datetime.utcnow().isoformat()
From string:
my_date = datetime.datetime.fromisoformat(my_date_string)
Try using dateutil
. It has a parse that will attempt to convert your string back into a datetime
object.
>>> from dateutil import parser
>>> strtime = str(datetime.now())
>>> strtime
'2012-11-13 17:02:22.395000'
>>> parser.parse(strtime)
datetime.datetime(2012, 11, 13, 17, 2, 22, 395000)
You can then subtract one datetime
from another and get a timedelta
object detailing the difference in time.