如何在 Python 中比较日期和日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3278999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:23:54  来源:igfitidea点击:

How can I compare a date and a datetime in Python?

python

提问by Mridang Agarwalla

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

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

采纳答案by kennytm

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

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

if item_date.date() > from_date:

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

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

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

to eliminate the time part afterwards.

以消除之后的时间部分。

回答by samarth

I am trying to compare date which are in string format like '20110930'

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

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

回答by tobixen

In my case, I get two objects in and I don't know if it's date or timedate objects. Converting to date won't be good as I'd be dropping information - two timedate objects with the same date should be sorted correctly. I'm OK with the dates being sorted before the datetime with same date.

在我的例子中,我得到了两个对象,我不知道它是 date 还是 timedate 对象。转换为日期不会好,因为我会丢弃信息 - 应该正确排序两个具有相同日期的 timedate 对象。我可以将日期排序在具有相同日期的日期时间之前。

I think I will use strftime before comparing:

我想我会在比较之前使用 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

Not elegant, but should work out. I think it would be better if Python wouldn't raise the error, I see no reasons why a datetime shouldn't be comparable with a date. This behaviour is consistent in python2 and python3.

不优雅,但应该工作。我认为如果 Python 不引发错误会更好,我认为没有理由不能将日期时间与日期进行比较。这种行为在 python2 和 python3 中是一致的。

回答by tobixen

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date... convert the date to a datetime using this construct:

这是另一种观点,“被盗”从评论中无法比较 datetime.datetime 到 datetime.date...使用此构造将日期转换为日期时间:

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

Suggestion:

建议:

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

回答by Peko Chan

Create and similar object for comparison works too ex:

用于比较的创建和类似对象也适用,例如:

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