短日期格式仍有时间

nag*_*m97 -1 python date strptime

我正在编写一个python脚本的日期问题.为什么这是假的?我不明白为什么00:00:00仍然存在,即使我只明确要求日,月,年?

date1 = datetime.strptime('22 Dec 2016', '%d %b %Y') <-- 2016-12-12 00:00:00
date2 = datetime.today().date()
print(date1==date2)  # False
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

您正在比较datetime对象和date对象; datetime.strptime() 总是产生一个datetime实例; 即使时间设置为午夜,这仍然是日期和时间的组合.

要仅比较日期,您需要明确地进行比较.

或者:

date1.date() == date2  # extract the date, compare to the other date
Run Code Online (Sandbox Code Playgroud)

要么

from datetime import time

# compare the datetime to another datetime with midnight
date1 == datetime.combine(date2, time.min)
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你清理它,现在确实有意义. (2认同)