如何在Python中比较日期? [英] How to compare dates in Python?

查看:681
本文介绍了如何在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 datetimes is a timedelta. Datetimes are comparable with each other, as are timedeltas.

您有2个选择:


  • 从给定的值中减去另一个 datetime ,然后比较所得的 timedelta 与您还给出的 timedelta

  • 转换将timedelta 添加到 datetime ,方法是将其添加或减去到另一个 datetime ,然后比较得到的 datetime 与您提供的 datetime

  • Subtract another datetime from the one you've given, and compare the resulting timedelta with the timedelta you've also given.
  • Convert the timedelta to a datetime by adding or subtracting it to another datetime, and then compare the resulting datetime with the datetime you've given.

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

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