Generating all dates within a given range in python
I have two string variables which contain dates in yyyy-mm-dd format as follows :
date1 = '2011-05-03'
date2 = '2011-05-10'
I want to write code that generates all dates in the range date1 to date2. How can this be done in Python?
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
>>>
from dateutil import rrule, parser
date1 = '2011-05-03'
date2 = '2011-05-10'
dates = list(rrule.rrule(rrule.DAILY,
dtstart=parser.parse(date1),
until=parser.parse(date2)))
print dates
Since dateutil is not a standard library, you will have to install it as a separate package. See the documentation for further details regarding the format (especially dayfirst
and yearfirst
switches).
Pandas is great for time series in general, and has direct support both for date ranges and date parsing (it's automagic).
import pandas as pd
date1 = '2011-05-03'
date2 = '2011-05-10'
mydates = pd.date_range(date1, date2).tolist()
It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range
.
See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps
链接地址: http://www.djcxy.com/p/18476.html上一篇: 用Python获取本月的最后一天
下一篇: 在python中生成给定范围内的所有日期