love2code love2code - 6 months ago 10
Python Question

Python datetime objects fail to match

I have 2 date time objects:

dt1 = 2016-04-18 20:15:07
dt2 = 2016-04-18 20:15:07+00:00


and I want to compare these 2 which should give me true as both are technically same. but when I do :

if(dt1 == dt2):
print("times match!)


I always get a false condition here. Any pointers on how to get over this?

Answer

I assume that dt1 and dt2 are string

import datetime

dt1 = "2016-04-18 20:15:07"
dt2 = "2016-04-18 20:15:07+00:00"


d1 = datetime.datetime.strptime(dt1, "%Y-%m-%d %H:%M:%S")
d2 = datetime.datetime.strptime(dt2, "%Y-%m-%d %H:%M:%S+%f:00")

print(d1)
print(d2)

if d1 == d2:
    print("times match!")
Comments