如何在 Python 中比较日期和日期时间? [英] How can I compare a date and a datetime in Python?

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

问题描述

这是我正在尝试执行的一个小片段:

<预><代码>>>>从日期时间导入 *>>>item_date = datetime.strptime('7/16/10', "%m/%d/%y")>>>from_date = date.today()-timedelta(days=3)>>>打印类型(item_date)<输入'日期时间.日期时间'>>>>打印类型(from_date)<输入'datetime.date'>>>>如果 item_date >从日期:...打印项目较新"...回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:无法将 datetime.datetime 与 datetime.date 进行比较

我似乎无法比较日期和日期时间值.比较这些的最佳方法是什么?我应该将日期时间转换为日期,反之亦然?我如何在它们之间转换.

(一个小问题,但似乎有点令人困惑.)

解决方案

使用 .date() 方法将日期时间转换为日期:

if item_date.date() >从日期:

或者,您可以使用 datetime.today() 而不是 date.today().你可以使用

from_date = from_date.replace(小时=0,分钟=0,秒=0,微秒=0)

消除之后的时间部分.

Here's a little snippet that I'm trying execute:

>>> from datetime import *
>>> item_date = datetime.strptime('7/16/10', "%m/%d/%y")
>>> from_date = date.today()-timedelta(days=3)
>>> print type(item_date)
<type 'datetime.datetime'>
>>> print type(from_date)
<type 'datetime.date'>
>>> if item_date > from_date:
...     print 'item is newer'
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.date

I can't seem to compare the date and the datetime values. What would be the best way to compare these? Should I convert the datetime to date or vice-versa? How do i convert between them.

(A small question but it seems to be a little confusing.)

解决方案

Use the .date() method to convert a datetime to a date:

if item_date.date() > from_date:

Alternatively, you could use datetime.today() instead of date.today(). You could use

from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)

to eliminate the time part afterwards.

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

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