Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pandas.date_range() to generate multiple datetimes, two dates per week

I'm using pd.date_range(start_date, end_date, freq='W-MON') to generate weekly frequency datetimes every Monday between start_date=2017-01-01 and end_date=2017-12-31, which means approximately 4 datetimes are generated per month. How to generate 8 datetimes per month instead i.e. generate 2 datetimes per week but on different days in a week, say Monday and any other day apart from Saturday or Sunday?

like image 933
DougKruger Avatar asked Feb 04 '23 20:02

DougKruger


1 Answers

There are at-least two ways of achieving this:

1) You can probably choose a weekly frequency corresponding to a different day of the week and take union of them which sorts the indices nicely and appends them.

start_date = "2017-01-01"
end_date = "2017-12-31"

d1 = pd.date_range(start_date, end_date, freq="W-MON")
d2 = pd.date_range(start_date, end_date, freq="W-TUE")

d1.union(d2)

2) A simpler way would be to create an offset corresponding to an extra Day. Followed by the same union operation.

from pandas.tseries.offsets import Day

d1.union(d1 + Day(1))

Both approaches produce:

DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-09', '2017-01-10',
               '2017-01-16', '2017-01-17', '2017-01-23', '2017-01-24',
               '2017-01-30', '2017-01-31',
               ...
               '2017-11-27', '2017-11-28', '2017-12-04', '2017-12-05',
               '2017-12-11', '2017-12-12', '2017-12-18', '2017-12-19',
               '2017-12-25', '2017-12-26'],
              dtype='datetime64[ns]', length=104, freq=None)
like image 70
Nickil Maveli Avatar answered Feb 07 '23 18:02

Nickil Maveli