在python中生成给定范围内的所有日期 [英] Generating all dates within a given range in python
本文介绍了在python中生成给定范围内的所有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个字符串变量,其中包含yyyy-mm-dd格式的日期,如下所示:
I have two string variables which contain dates in yyyy-mm-dd format as follows :
date1 = '2011-05-03'
date2 = '2011-05-10'
我想写生成范围从date1到date2的所有日期的代码。如何在Python中完成?
I want to write code that generates all dates in the range date1 to date2. How can this be done in Python?
推荐答案
日期可以相互比较,就像数字一样,与datetime.timedelta对象相关的数学。没有理由在这里使用dateutil,没有理由硬编码迭代次数(9)。这真的变得与处理普通旧数字的方式类似。
Dates can be compared to each other just like numbers, and you can do date-related math with the datetime.timedelta object. There's no reason to use dateutil here, and there's no reason to hard-code the number of iterations a la 'range(9)'. This really becomes similar to how you'd deal with plain old numbers.
>>> import datetime
>>> date1 = '2011-05-03'
>>> date2 = '2011-05-10'
>>> start = datetime.datetime.strptime(date1, '%Y-%m-%d')
>>> end = datetime.datetime.strptime(date2, '%Y-%m-%d')
>>> step = datetime.timedelta(days=1)
>>> while start <= end:
... print start.date()
... start += step
...
2011-05-03
2011-05-04
2011-05-05
2011-05-06
2011-05-07
2011-05-08
2011-05-09
2011-05-10
>>>
这篇关于在python中生成给定范围内的所有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文