简体   繁体   English

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

[英]How can I compare a date and a datetime in Python?

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.) (一个小问题,但似乎有点混乱。)

Use the .date() method to convert a datetime to a date:使用.date()方法将日期时间转换为日期:

if item_date.date() > from_date:

Alternatively, you could use datetime.today() instead of date.today() .或者,您可以使用datetime.today()而不是date.today() You could use你可以用

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

to eliminate the time part afterwards.以消除之后的时间部分。

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

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

In my case, I get two objects in and I don't know if it's date or timedate objects.在我的例子中,我得到了两个对象,我不知道它是 date 还是 timedate 对象。 Converting to date won't be good as I'd be dropping information - two timedate objects with the same date should be sorted correctly.转换为日期不会好,因为我会丢弃信息 - 应该正确排序两个具有相同日期的 timedate 对象。 I'm OK with the dates being sorted before the datetime with same date.我可以将日期排序在具有相同日期的日期时间之前。

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.我认为如果 Python 不引发错误会更好,我认为没有理由不能将日期时间与日期进行比较。 This behaviour is consistent in python2 and python3.这种行为在 python2 和 python3 中是一致的。

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

I got you bro我找到你了兄弟

you can use timetuple function to compare between date obj and datetime obj您可以使用 timetuple function 来比较日期对象和日期时间对象

>>> from datetime import datetime               
>>> date_obj=datetime.utcnow().date() 
>>> type(date_obj)
<type 'datetime.date'>
>>> datetime_obj=datetime.utcnow()    
>>> type(datetime_obj)            
<type 'datetime.datetime'>
>>> datetime_obj.timetuple()          
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=2, tm_min=12, tm_sec=43, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> date_obj.timetuple()     
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> type(datetime_obj.timetuple())
<type 'time.struct_time'>
>>> type(date_obj.timetuple()) 
<type 'time.struct_time'>
>>> date_obj.timetuple()<datetime_obj.timetuple()
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM