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

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

Question: Can I get any suggestions on how to do this and how to process the months of 28, 29, 30 or 31 days in each. I think I can do this by extracting the numbers as integers through division / modding of degrees 10, and then increasing these numbers as such with specific conditions above, but I feel that there should be an easier way to do this.

+5
source share
3 answers

You do not need to reinvent the wheel. Just parse the strings in 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
+19
source

An alternative solution without use rrulegoes 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'))

Conclusion:

20150101
20150102
20150103
<snip>
20150205
20150206
+2
source

You can use pandas.date_range,

import pandas

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

which will 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')
0
source

All Articles