简体   繁体   中英

How to get all dates (month, day and year) between two dates in python?

Situation: I am trying to construct a simple method that accepts two different integers that represent two different dates. 20120525 for May 25, 2012 and 20120627 for June 26, 2012 as an example. I want this method to return a list of these integer types that represent all days between the two date parameters.

Question: Could I get any suggestions on how to do this and how to handle months of either 28, 29, 30 or 31 days in each. I think I can do this by extracting the numbers as integers through division/modding of powers of 10, and then incrementing these numbers as such with the particular conditions above, but I feel like there must be an easier way to do this.

You don't have to reinvent the wheel. Just parse the strings into datetime objects and let python do the math for you:

from dateutil import rrule
from datetime import datetime

a = '20120525'
b = '20120627'

for dt in rrule.rrule(rrule.DAILY,
                      dtstart=datetime.strptime(a, '%Y%m%d'),
                      until=datetime.strptime(b, '%Y%m%d')):
    print dt.strftime('%Y%m%d')

prints

20120525
20120526
20120527
…
20120625
20120626
20120627

An alternative solution without using rrule goes here:

import datetime

d1 = datetime.date(2015, 1, 1)
d2 = datetime.date(2015, 2, 6)
days = [d1 + datetime.timedelta(days=x) for x in range((d2-d1).days + 1)]

for day in days:
    print(day.strftime('%Y%m%d'))

Output:

20150101
20150102
20150103
<snip>
20150205
20150206

You can use pandas.date_range ,

import pandas

pd.date_range('2012-05-25', '2012-06-27', freq='D')

which would produce,

DatetimeIndex(['2012-05-25', '2012-05-26', '2012-05-27', '2012-05-28',
               '2012-05-29', '2012-05-30', '2012-05-31', '2012-06-01',
               ...
               '2012-06-22', '2012-06-23', '2012-06-24', '2012-06-25',
               '2012-06-26', '2012-06-27'],
               dtype='datetime64[ns]', freq='D')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM