【问题标题】:How can I compare a date and a datetime in Python?如何在 Python 中比较日期和日期时间?
【发布时间】:2010-07-19 06:58:08
【问题描述】:

这是我正在尝试执行的一个小 sn-p:

>>> 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

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

(一个小问题,但似乎有点混乱。)

【问题讨论】:

标签: python


【解决方案1】:

使用the .date() method 将日期时间转换为日期:

if item_date.date() > from_date:

或者,您可以使用datetime.today() 代替date.today()。你可以使用

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

消除之后的时间部分。

【讨论】:

  • 我认为这是最好的答案,如果它给出 item_date 将始终是一个日期时间并且 from_date 将始终是一个日期。我来到这里是因为我想对包含日期和日期时间的列表进行排序。就我而言,上述方法可能是最糟糕的。
  • 为什么需要转换?我认为内部 python 对datedatetime 使用 unixtimestamp。或者date 是否对资源进行了更多优化,因为它只查找日期而不是时间?
【解决方案2】:

这是另一种保留信息的方法,以防两个输入都是日期时间而不是日期,从can't compare datetime.datetime to datetime.date 的评论中“窃取”...使用此构造将日期转换为日期时间:

datetime.datetime(d.year, d.month, d.day)

建议:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

【讨论】:

    【解决方案3】:

    我正在尝试比较字符串格式的日期,例如 '20110930'

    benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 
    
    actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")
    
    if actualDate.date() < benchMark.date():
        print True
    

    【讨论】:

    • 如果有字符串格式YYYYMMDD字符串比较相当于转换成日期比较日期,效率更高。
    【解决方案4】:

    就我而言,我得到了两个对象,但我不知道它是日期对象还是时间对象。转换为日期不会很好,因为我会删除信息 - 两个具有相同日期的 timedate 对象应该正确排序。我可以将日期排序在具有相同日期的日期时间之前。

    我想我会在比较之前使用 strftime:

    >>> foo=datetime.date(2015,1,10)
    >>> bar=datetime.datetime(2015,2,11,15,00)
    >>> foo.strftime('%F%H%M%S') > bar.strftime('%F%H%M%S')
    False
    >>> foo.strftime('%F%H%M%S') < bar.strftime('%F%H%M%S')
    True
    

    不优雅,但应该可以解决。我认为如果 Python 不引发错误会更好,我看不出为什么日期时间不应该与日期相比较。这种行为在 python2 和 python3 中是一致的。

    【讨论】:

      【解决方案5】:

      创建和类似的对象也可以进行比较 例如:

      from datetime import datetime, date
      
      now = datetime.now()
      today = date.today()
      
      # compare now with today
      two_month_earlier = date(now.year, now.month - 2, now.day)
      if two_month_earlier > today:
          print(True)
      
      two_month_earlier = datetime(now.year, now.month - 2, now.day)
      if two_month_earlier > now:
         print("this will work with datetime too")
      

      【讨论】:

        猜你喜欢
        • 2015-07-20
        • 1970-01-01
        • 2022-01-02
        • 2012-04-20
        • 2012-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-18
        相关资源
        最近更新 更多