1

I have a string that I've converted to a datetime object using parse.

time = 'Tue, 30 Sep 2014 16:19:08 -0700 (PDT)'
date_object = parse(time)

I want to find the time that has elapsed since then. I tried using datetime.datetime.now() and subtract the two, but they are different format and was throwing an error.

What is the best way to do this?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Morgan Allen
  • 3,291
  • 8
  • 62
  • 86
  • related: [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/q/26313520/4279) – jfs Apr 04 '16 at 02:41

2 Answers2

6

Make the timezone aware datetime object and substract date_object from it:

>>> from dateutil.parser import parse
>>> time = 'Tue, 30 Sep 2014 16:19:08 -0700 (PDT)'
>>> date_object = parse(time)
>>>
>>> from datetime import datetime
>>> import pytz
>>> now = datetime.now(pytz.timezone('US/Pacific'))
>>> now - date_object
datetime.timedelta(550, 84210, 337036) 
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • note: you could pass any timezone to `.now()` e.g., `now = datetime.now(pytz.utc)` -- it does not change the result. – jfs Apr 04 '16 at 02:50
1

If you have a timezone-aware datetime object then you could convert it to UTC, to find the elapsed time easily:

from datetime import datetime

# <utc time> = <local time> - <utc offset>
then_utc = date_object.replace(tzinfo=None) - date_object.utcoffset()
now = datetime.utcnow()
elapsed = now - then_utc

The explanation of why you should not use datetime.now() to get the elapsed time see in here.


You could parse the time string and get the elapsed time using only stdlib:

>>> time_string = 'Tue, 30 Sep 2014 16:19:08 -0700 (PDT)'
>>> from email.utils import parsedate_tz, mktime_tz
>>> then = mktime_tz(parsedate_tz(time_string))
>>> import time
>>> now = time.time()
>>> elapsed_seconds = now - then
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670