1

How do I compare a datetime object of this format

"Thu, 15 Jan 2015 06:35:37 GMT" with the current time ?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Shan
  • 39
  • 3
  • 1
    With [`datetime`](https://docs.python.org/2/library/datetime.html). – jonrsharpe Jan 16 '15 at 07:01
  • there are two questions: 1. how to [convert the string (`str` object) into `datetime` object](http://stackoverflow.com/q/26435530/4279) 2. How to [compare it with the current date](http://stackoverflow.com/a/26313848/4279). – jfs Jan 16 '15 at 10:12

3 Answers3

1

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
>>> 
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
0

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.

Andrew Gorcester
  • 19,595
  • 7
  • 57
  • 73
0
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
jfs
  • 399,953
  • 195
  • 994
  • 1,670