How to compare dates (not time) in python

I have 2 datetime objects. One only has a date, and the other has a date and time. I want to compare only dates (not time). This is what I have:

d2=datetime.date(d1.year,d1.month,d1.day) print d2 == d1.date 

It outputs false. Any idea why?

Thanks!

+9
source share
4 answers
 d1.date() == d2.date() 

From the Python doc :

datetime.date() A return date object with the same year, month, and day.

+22
source

Transfer your datetime object to a date object. Once they are of the same type, a comparison will make sense.

 if d2.date() == d1.date(): print "same date" else: print "different date" 

In your case above: -

 In [29]: d2 Out[29]: datetime.date(2012, 1, 19) In [30]: d1 Out[30]: datetime.datetime(2012, 1, 19, 0, 0) 

So,

 In [31]: print d2 == d1.date() True 

All you needed for your case was to make sure that you execute the date method with parentheses () .

+4
source
 >>> datetime.date.today() == datetime.datetime.today().date() True 

More details

+1
source

TL & DR:

The DateTime object has a built-in function called date (). You can use this to get the date of a datetime object only.

Example:

 current_time_dt_object = datetime.datetime.now() current_time_only_date = current_time_dt_object.date() 

Now you can use this current_time_only_date, like any equality operation you want.

0
source

All Articles