本文介绍了将 Python 中的日期与 datetime 进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
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)]
这篇关于将 Python 中的日期与 datetime 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!