Morgan Allen Morgan Allen - 7 months ago 20
Python Question

Subtracting two datetime objects

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?

Answer

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
Comments