user9013730
user9013730

Reputation:

Comparing 2 dates in Python did not work as expected

I would like to compare 2 dates in Python. However, the following program does not working as expected. As you can see in the output, today is 2019-08-11. Unfortunately, Python evaluate it as False even though it's actually true, right?

import datetime

today = datetime.date.today()
day1 = datetime.datetime(2019, 8, 11)

print(f"Today's date is {today}")

if today == day1:
    print('today is day1')
else:
    print('today is not day1')

Output

user@linux:~$ py compare2dates.py 
Today's date is 2019-08-11
today is not day1
user@linux:~$ 

What went wrong with this code and how do I fix it?

Upvotes: 4

Views: 301

Answers (1)

AAA
AAA

Reputation: 3670

This is simply because you are using datetime rather than date. If you printed day1 you would notice it is a datetime with a timestamp:

day1 = datetime.datetime(2019, 8, 10)
print(f"day1 is {day1}")

day1 is 2019-08-10 00:00:00

To avoid the error, change your code as follows:

import datetime

today = datetime.date.today()
day1 = datetime.date(2019, 8, 11)

print(f"Today's date is {today}")

if today == day1:
    print('today is day1')
else:
    print('today is not day1')

Upvotes: 4

Related Questions