Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)

Post a Comment for "Using Pandas.date_range() To Generate Multiple Datetimes, Two Dates Per Week"