1

I have one datetime object

2016-04-11 19:46:46-04:00

and

2016-04-25 09:35:18.464966 (this one is datetime.datetime.now())

How do I get them to the same format so I can subtract them?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Morgan Allen
  • 3,291
  • 8
  • 62
  • 86

3 Answers3

1

You can use dateutil.parser.

from dateutil.parser import *
import datetime

date1="2016-04-11 19:46:46-04:00"
date2=datetime.datetime.now()
updated_date1=parse(date1, ignoretz=True) #Ignoring TimeZone
updated_date2=parse(str(date2))
result=updated_date2 - updated_date1
print result
Prabhakar
  • 1,138
  • 2
  • 14
  • 30
  • it is wrong if the current utc offset is not `-04:00` (e.g., if there was a DST transition between now and then or if the local timezone is different). Don't ignore the timezone information. Convert `date1` to utc (`date1.replace(tzinfo=None) - date1.utcoffset()`) and use `.utcnow()` instead of `.now()`, to find the time difference. – jfs Apr 26 '16 at 06:42
0

Your first date string has a time zone and datetime.datetime.now() is timezone free.

You can parse the first string like so:

>>> d1=datetime.datetime.strptime("2016-04-11 19:46:46-0400", "%Y-%m-%d %H:%M:%S%z")
>>> print(d1)
2016-04-11 19:46:46-04:00

Or, if you have the : in the time zone offset, you need to remove it with a regex or partition:

>>> datetime.datetime.strptime(''.join('2016-04-11 19:46:46-04:00'.rpartition(':')[0::2]), "%Y-%m-%d %H:%M:%S%z")
datetime.datetime(2016, 4, 11, 19, 46, 46, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

Note that I have done this in Python 3 since Python prior to 3.2 is spotty supporting the %z directive. (It is only supported if the C library used to build Python supports it. Python 3.2 and later has native support.)

Now to compare or add/subtract you either need to add a timezone to datetime.datetime.now() or remove it from d1. Here is how to remove it:

>>> d1.replace(tzinfo=None)
datetime.datetime(2016, 4, 11, 19, 46, 46)

Then you can subtract:

>>> d1.replace(tzinfo=None)-datetime.datetime.now()
datetime.timedelta(-14, 42738, 274649)

If you want to make the timezone free time the same timezone, you can do:

>>> d1-datetime.datetime.now().replace(tzinfo=d1.tzinfo)
datetime.timedelta(-14, 41899, 435274)
dawg
  • 98,345
  • 23
  • 131
  • 206
0

The original dictionary looks like this {"name": "Date", "value": "Mon, 11 Apr 2016 19:46:46 -0400"}
...
this one is datetime.datetime.now()

To find elapsed seconds since the given time (specified as a string):

import time
from email.utils import parsedate_tz, mktime_tz

d = {"name": "Date", "value": "Mon, 11 Apr 2016 19:46:46 -0400"}
then = mktime_tz(parsedate_tz(d['value']))
now = time.time()
elapsed_seconds = now - then

Don't confuse datetime objects (type(obj) == datetime.datetime) and strings (type(obj) == str).

jfs
  • 399,953
  • 195
  • 994
  • 1,670