Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Infi Avatar asked Nov 13 '12 06:11

Infi


People also ask

Does datetime return a string Python?

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.

Which function converts a datetime object to a string?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format.


1 Answers

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
like image 119
bereal Avatar answered Sep 30 '22 16:09

bereal