How to Compare Dates Only (And Not the Time) in Python

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!

5 Answers

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

From the Python doc:

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

2

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 ().

For those who wants to compare specific date with today date.

import datetime

# Set specific date
date = '2020-11-21'

# Cast specific date to Date Python Object
date = datetime.datetime.strptime(date, '%Y-%m-%d').date()

# Get today date with Date Python Object
today = datetime.date.today()

# Compare the date
isYesterday = date < today
isToday     = date == today
isTomorrow  = date > today
0
>>> datetime.date.today() == datetime.datetime.today().date()
True

For more info

TL&DR:

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

Example:

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

You can now use this current_time_only_date as do any equality operation you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest