0

I want to create a DatetimeIndex representing months but the number of days between successive months differs in a periodic manner.

I want it so that every third index the date increases by 5 weeks (35 days) and for all others only 4 weeks (28 days).

As an example I want an output to be like the following:

DatetimeIndex(
['2004-08-01', # start
'2004-08-29', # 28 days added
'2004-10-03', # 35 days added
'2004-10-31', # 28 days added
'2004-11-28', # 28 days added    
'2005-01-02', # 35 days added
'2005-01-30', # 28 days added
'2005-02-27', # 28 days added
'2005-04-03', # 35 days added
'2005-05-01', # 28 days added
'2005-05-29']) # 28 days added

Is something like this possible and if so how can I use pandas to achieve it?

Luca Guarro
  • 1,085
  • 1
  • 11
  • 25

1 Answers1

0

Calculate the increments (28, 28, 35 ...) first, convert that to a time delta and then add a start date to it:

import pandas as pd
import numpy as np

days = (4 + (np.arange(1, 10) % 3 == 0)) * 7
days
# array([28, 28, 35, 28, 28, 35, 28, 28, 35])

start_date = (pd.to_datetime('2004-09-03') - pd.to_timedelta(28, unit='D'))
pd.to_timedelta(days.cumsum(), unit='D') + start_date
# DatetimeIndex(['2004-09-03', '2004-10-01', '2004-11-05', '2004-12-03',
#                '2004-12-31', '2005-02-04', '2005-03-04', '2005-04-01',
#                '2005-05-06'],
#               dtype='datetime64[ns]', freq=None)
Psidom
  • 209,562
  • 33
  • 339
  • 356