仅按日期比较日期时间对象 [英] Comparing datetime objects by date only

查看:139
本文介绍了仅按日期比较日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 datetime 对象具有相同的日,月和年,说:

I have two datetime objects having same day, month and year, say:

test_date = datetime.datetime(2014, 4, 25, 11, 57, 56)

(以上日期被创建,如 datetime.utcfromtimestamp(utc_timestamp))和

(above date is created like datetime.utcfromtimestamp(utc_timestamp)) and

now_date  = datetime.datetime(2014, 4, 25, 12, 40, 19, 705355)

(以上日期被创建为 datetime.now())。当我说

(above date is created like datetime.now()). When I say

now_date==test_date

True 时,我得到 False 。如何正确比较?

I get False when it should be True. How can I compare correctly?

推荐答案

您正在比较整个 datetime 对象,包括时间(不匹配)。相反,只需比较 日期 部分:

You are currently comparing the whole datetime object, including the time (which doesn't match). Instead, just compare the date part:

>>> now_date.date() == test_date.date()
True

这篇关于仅按日期比较日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆