如何在Python中比较日期? [英] How to compare dates in Python?
本文介绍了如何在Python中比较日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要查看日期是否超过X天。我如何在Python中做到这一点?
I need to see if a date has more than X days. How can I do this in Python?
我已经测试过类似的东西:
I have tested something like:
if datetime.date(2010, 1, 12) > datetime.timedelta(3):
我收到错误:
TypeError: can't compare datetime.date to datetime.timedelta
有关如何实现此目标的任何线索?
Any clue on how to achieve this?
推荐答案
您无法比较 datetime
到< a href = http://docs.python.org/py3k/library/datetime.html#timedelta-objects rel = noreferrer> timedelta
。 timedelta
表示持续时间, datetime
表示特定时间点。 差异与两个 datetime 的区别 code> s是
timedelta
。日期时间彼此可比, timedelta
s也是如此。
You can't compare a datetime
to a timedelta
. A timedelta
represents a duration, a datetime
represents a specific point in time. The difference of two datetime
s is a timedelta
. Datetimes are comparable with each other, as are timedelta
s.
您有2个选择:
- 从给定的值中减去另一个
datetime
,然后比较所得的timedelta
与您还给出的timedelta
。 - 转换
将timedelta
添加到datetime
,方法是将其添加或减去到另一个datetime
,然后比较得到的datetime
与您提供的datetime
。
- Subtract another
datetime
from the one you've given, and compare the resultingtimedelta
with thetimedelta
you've also given. - Convert the
timedelta
to adatetime
by adding or subtracting it to anotherdatetime
, and then compare the resultingdatetime
with thedatetime
you've given.
这篇关于如何在Python中比较日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文