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?
We use the Python strftime() method to convert a datetime to a string. The Python strftime() function is in charge of returning a string representing date and time using a date, time, or datetime object. It accepts one or more lines of formatted code as input and returns the string representation.
The ToString() method of the DateTime class is used to convert a DateTime date object to string format.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With