4

Given two dates, for example:

December 1, 2017
June 1, 2018

I want to get this result:

January 1, 2018
February 1, 2018
March 1, 2018
April 1, 2018
May 1, 2018
June 1, 2018

Moreover, I also want to modify the intervals. In the case above, the interval is monthly. I also want it to become quarterly and semi-annually.

So, given December 1, 2017 and June 1, 2018, it will generate March 1, 2018 for semi-annual and so on...

I also want it inclusive which means that the end date should also be included

Is there a python package or function for this?

JM Lontoc
  • 211
  • 4
  • 15
  • 2
    Possible duplicate of [Python list of first day of month for given period](https://stackoverflow.com/questions/22696662/python-list-of-first-day-of-month-for-given-period) – tommy.carstensen Dec 02 '17 at 03:05
  • 2
    What have you tried so far? Also check this question: https://stackoverflow.com/questions/993358/creating-a-range-of-dates-in-python – tommy.carstensen Dec 02 '17 at 03:11

3 Answers3

6

Pendulum — and specifically its 'range' function — is good for this.

It will give you both the monthly interval dates and what I take you to mean three-month interval dates.

>>> import pendulum
>>> start = pendulum.Pendulum(2017, 12, 1)
>>> end = pendulum.Pendulum(2018, 6, 1)
>>> period = pendulum.period(start, end)
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months')]
['2017-12-01', '2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01', '2018-06-01']
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months', 3)]
['2017-12-01', '2018-03-01', '2018-06-01']
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
4

Pandas has a pretty good datetime library of functions.

import pandas as pd

start = pd.to_datetime('December 1, 2017')
end = pd.to_datetime('June 1, 2018')

Get first day of every month:

pd.date_range(start, end, freq='MS').strftime('%B %d, %Y').tolist()

['December 01, 2017',
 'January 01, 2018',
 'February 01, 2018',
 'March 01, 2018',
 'April 01, 2018',
 'May 01, 2018',
 'June 01, 2018']

Where you can use this chart for freq values.

pd.date_range(start, end, freq='QS').strftime('%B %d, %Y').tolist()

['January 01, 2018', 'April 01, 2018']
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0
from datetime import datetime

def mrange(d1, d2,s=0): #s for semi-annual
    while d1<d2:
        y,m=divmod(d1.month+1,12)
        d1=datetime(d1.year+y,m,1)
        if not s or d1.month==3 :
            yield d1


d1='December 1, 2017'
d2='June 1, 2018'
d1 = datetime.strptime(d1,'%B %d, %Y')
d2 = datetime.strptime(d2,'%B %d, %Y')
for s in mrange(d1, d2,):print(s.strftime('%B %d, %Y'))
print('--'*25)
for s in mrange(d1, d2,1):print(s.strftime('%B %d, %Y'))
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59