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

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

>>> datetime.date.today() == datetime.datetime.today().date()
True

For more info


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


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

From the Python doc:

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