Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates only (and not the time) in python

Tags:

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

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

It prints out false. Any idea why?

Thank you!

like image 851
Dao Lam Avatar asked Nov 05 '12 07:11

Dao Lam


People also ask

How do you compare only the date and not time?

Fortunately you can use the INT() function in Excel to extract just the date from a datetime value, which allows you to easily compare dates while ignoring the time.

How do I compare only dates in Python?

The DateTime Object has a built in function called date(). You can use this to get the date only of the datetime object. You can now use this current_time_only_date as do any equality operation you want.

How do I remove the time from a date in Python?

To remove the time from a datetime object in Python, convert the datetime to a date using date(). You can also use strftime() to create a string from a datetime object without the time. When working in Python, many times we need to create variables which represent dates and times.


2 Answers

d1.date() == d2.date()

From the Python doc:

datetime.date() Return date object with same year, month and day.

like image 133
Nicolas Avatar answered Oct 04 '22 04:10

Nicolas


Cast your datetime object into a date object first. Once they are of the same type, the comparison will make sense.

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

For 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 you are executing the date method with the brackets ().

like image 20
Calvin Cheng Avatar answered Oct 04 '22 02:10

Calvin Cheng