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