如何在Python中比较日期?
我需要查看某个日期是否超过 X 天。我怎样才能在Python中做到这一点?
我已经测试过类似的内容:
if datetime.date(2010, 1, 12) > datetime.timedelta(3):
我收到错误:
TypeError: can't compare datetime.date to datetime.timedelta
有关如何实现此目标的任何线索?
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):
I got the error:
TypeError: can't compare datetime.date to datetime.timedelta
Any clue on how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法比较
datetime
到timedelta
。timedelta
表示持续时间,datetime
表示特定时间点。两个datetime
的差异是一个时间增量
。日期时间彼此之间具有可比性,timedelta
也是如此。您有 2 个选择:
datetime
,然后将所得的timedelta
与您也给定的timedelta
进行比较。timedelta
与另一个datetime
相加或相减,将其转换为datetime
,然后将生成的datetime
与您指定的日期时间
。You can't compare a
datetime
to atimedelta
. Atimedelta
represents a duration, adatetime
represents a specific point in time. The difference of twodatetime
s is atimedelta
. Datetimes are comparable with each other, as aretimedelta
s.You have 2 options:
datetime
from the one you've given, and compare the resultingtimedelta
with thetimedelta
you've also given.timedelta
to adatetime
by adding or subtracting it to anotherdatetime
, and then compare the resultingdatetime
with thedatetime
you've given.比较苹果和橙子总是很困难!您试图将“2010 年 1 月 12 日”(固定时间点)与“3 小时”(持续时间)进行比较。这毫无意义。
如果您问的是“我的日期时间是否在该月的第 n 天之后”,那么您可以执行以下操作:
Comparing apples and oranges is always very hard! You are trying to compare "January 12, 2010" (a fixed point in time) with "3 hours" (a duration). There is no sense in this.
If what you are asking is "does my
datetime
fall after the nth day of the month" then you can do :