Date Range using frequency and periods

1.5k Views Asked by At

I built a routine that creates me a list of dates using different frequencies and also periods, the only thing I cannot get working is using the periods while using 'M' for end of the month entries.

def run_date_creator(start_date, end_date, steps, interval):
    #Interval: Days(d or D), Weeks (w or W), Month (m or M), Quarters (q or Q) and Years(y or Y) 
    start_date = pd.to_datetime(start_date) 
    end_date   = pd.to_datetime(end_date)
    if interval == 'd' or interval == 'D':
        dates = pd.date_range(start_date, end_date, freq=pd.tseries.offsets.DateOffset(days=1*steps))
    elif interval == 'w':
        dates = pd.date_range(start_date, end_date, freq=pd.tseries.offsets.DateOffset(days=7*steps))
    elif interval == 'bm' or interval == 'BM':
        dates = pd.date_range(start_date, end_date, freq=pd.tseries.offsets.DateOffset(months=1*steps))
    elif interval == 'em' or interval == 'EM':
        dates = pd.date_range(start_date, end_date, freq='M')
    elif interval == 'q' or interval == 'Q':
        dates = pd.date_range(start_date, end_date, freq=pd.tseries.offsets.DateOffset(months=3*steps))
    elif interval == 'y' or interval == 'Y':
        dates = pd.date_range(start_date, end_date, freq=pd.tseries.offsets.DateOffset(months=12*steps))
    return list(dates.strftime("%Y-%m-%d"))

start_date = '2017-1-1'
end_date  = '2017-12-31'

dates = run_date_creator(start_date, end_date , 2, 'em')

thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

You can specify steps in freq.

dates = pd.date_range(start_date, end_date, freq='%dM' % steps)