I'm trying to convert a string in the format:
Apr 18 17:19:42
to datetime so that I can compare the current time with that time and see if they are off by a minute. How do I do that?
As S1R has already pointed out, the strptime
method is what you want. You'll also need to specify the year, since its not included in your date string:
>>> import datetime
>>> s = "Apr 18 17:19:42"
>>> t = datetime.datetime.strptime(s, "%b %d %H:%M:%S")
>>> t
datetime.datetime(1900, 4, 18, 17, 19, 42)
>>> t = t.replace(year = 2012)
>>> n = datetime.datetime.now()
>>> n
datetime.datetime(2012, 4, 20, 10, 21, 42, 165657)
>>> d = n-t
>>> d.total_seconds()
147720.165657
strptime
is what you need, it is used to change a string to a datetime
So in your case it would be;
from datetime import datetime
todaysdate = datetime.strptime('Apr 18 17:19:42', '%b %d %H:%M:%S')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.