Comparing Datetime Objects By Date Only
I have two datetime objects having same day, month and year, say: test_date = datetime.datetime(2014, 4, 25, 11, 57, 56) (above date is created like datetime.utcfromtimestamp(utc_
Solution 1:
You are currently comparing the whole datetime
object, including the time (which doesn't match). Instead, just compare the date
part:
>>> now_date.date() == test_date.date()
True
Solution 2:
Since, you just want to compare the dates and not the time, you need to convert these to datetime.date
objects which strip out the time related information.
In [1]: import datetime
In [2]: test_date = datetime.datetime(2014, 4, 25, 11, 57, 56)
In [3]: now_date = datetime.datetime(2014, 4, 25, 12, 40, 19, 705355)
In [4]: now_date == test_date
Out[4]: False
In [5]: test_date = test_date.date()
In [6]: test_date
Out[6]: datetime.date(2014, 4, 25)
In [7]: now_date = now_date.date()
In [8]: now_date
Out[8]: datetime.date(2014, 4, 25)
In [9]: now_date == test_date
Out[9]: True
Post a Comment for "Comparing Datetime Objects By Date Only"