11

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.

jab
  • 5,673
  • 9
  • 53
  • 84
  • See also [iterating-through-a-range-of-dates-in-python](https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python) and [print-all-day-dates-between-two-dates](https://stackoverflow.com/questions/7274267/print-all-day-dates-between-two-dates) – J0ANMM Apr 17 '18 at 07:50

3 Answers3

26

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
eumiro
  • 207,213
  • 34
  • 299
  • 261
14

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
SaeX
  • 17,240
  • 16
  • 77
  • 97
7

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')
rth
  • 10,680
  • 7
  • 53
  • 77
  • 1
    There's an error in your code. The top line should read `import pandas as pd` – Haddock-san Jul 26 '21 at 16:01
  • 1
    But I wouldn't recommend this, using pandas library for a super simple function!! Using a national grid to charge a phone! – emanuel sanga Oct 12 '21 at 13:55
  • Clearly this only makes sense if you already use pandas for something else for your project. If you do, then it's a simpler solution than the ones above. – rth Oct 13 '21 at 08:45