Compare dates in Python with datetime

余生颓废 提交于 2019-12-22 10:28:05

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17768928/compare-dates-in-python-with-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!