How do I compare a datetime object of this format
"Thu, 15 Jan 2015 06:35:37 GMT" with the current time ?
How do I compare a datetime object of this format
"Thu, 15 Jan 2015 06:35:37 GMT" with the current time ?
You can use datetime
module to convert from datetime string into datetimetime object.
then get different between two datetime objects.
>>> from datetime import datetime
>>> a = datetime.strptime("Thu, 15 Jan 2015 06:35:37 GMT", "%a, %d %b %Y %H:%M:%S GMT", )
>>> b = datetime.strptime("Fri, 16 Jan 2015 07:40:40 GMT", "%a, %d %b %Y %H:%M:%S GMT", )
>>> c1 = b - a
>>> c1
datetime.timedelta(1, 3903)
>>> c1.days
1
>>> c1.total_seconds()
90303.0
>>> c1.seconds
3903
>>>
The easiest way is with the dateutil
package. First install dateutil
and then:
from dateutil.parser import parse
parsed_time = parse("Thu, 15 Jan 2015 06:35:37 GMT")
Then you can do from datetime import datetime
and get the current time with datetime.now()
, and you'll have two datetime objects you can compare however you like.
If you can't use dateutil
, you can still do it with datetime.strptime()
, but you'll have to specify the date string exactly which is quite fiddly. Refer to the standard library documentation in that case.
import time
from email.utils import parsedate_tz, mktime_tz
# Convert the input date string to "seconds since the epoch" (POSIX time)
timestamp = mktime_tz(parsedate_tz("Thu, 15 Jan 2015 06:35:37 GMT"))
# Compare it with the current time (ignoring leap seconds)
elapsed_seconds = time.time() - timestamp