我想在Python中比较2个日期。但是,以下程序无法正常工作。从输出中可以看到,今天是2019-08-11
。不幸的是,即使它实际上是真的,Python也会将其评估为False,对吧?
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')
输出
user@linux:~$ py compare2dates.py
Today's date is 2019-08-11
today is not day1
user@linux:~$
此代码出了什么问题以及如何解决?
答案 0 :(得分:5)
这仅仅是因为您使用的是datetime
而不是date
。如果您打印了day1
,您会注意到它是带有时间戳的日期时间:
day1 = datetime.datetime(2019, 8, 10)
print(f"day1 is {day1}")
day1是2019-08-10 00:00:00
为避免错误,请按如下所示更改代码:
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')