将 Python 中的日期与 datetime 进行比较

2022-01-25 00:00:00 python datetime time date compare

问题描述

So I have a list of dates:

[datetime.date(2013, 7, 9), datetime.date(2013, 7, 12), datetime.date(2013, 7, 15), datetime.date(2013, 7, 18), datetime.date(2013, 7, 22), datetime.date(2013, 7, 25)]

And I know today is:

date.today() 

For the sake of this post, today is datetime.date(2013, 7, 15)

I need to be able to generate a list of any future dates, including today if it's on the list.

The return statement would be:

[datetime.date(2013, 7, 15), datetime.date(2013, 7, 18), datetime.date(2013, 7, 22), datetime.date(2013, 7, 25)]

I know I can just iterate over a list and compare dates using a timedelta but there has to be an easier way..

解决方案

Comparing date with other date is possible.

date1 < date2 date1 is considered less than date2 when date1 precedes date2 in time.

>>> datetime.date(2013, 7, 15) < datetime.date(2013, 7, 16)
True
>>> datetime.date(2013, 7, 15) <= datetime.date(2013, 7, 16)
True
>>> datetime.date(2013, 7, 15) > datetime.date(2013, 7, 16)
False


>>> import datetime
>>> today = datetime.date(2013, 7, 15) # datetime.date.today()
>>> [d for d in dates if d >= today]
[datetime.date(2013, 7, 15), datetime.date(2013, 7, 18), datetime.date(2013, 7, 22), datetime.date(2013, 7, 25)]

相关文章