How can I generate a pandas date range with a frequency of Tue to Sat inclusive?

Viewed 958

I am trying to generate a datetime index with pandas that has a custom daily frequency.

At the moment, I can generate the following datetime index:

import pandas as pd
import datetime as dt

pd.date_range(start=dt.datetime(2020,8,28),end=dt.datetime(2020,9,30),freq='B')

DatetimeIndex(['2020-08-28', '2020-08-31', '2020-09-01', '2020-09-02',
               '2020-09-03', '2020-09-04', '2020-09-07', '2020-09-08',
               '2020-09-09', '2020-09-10', '2020-09-11', '2020-09-14',
               '2020-09-15', '2020-09-16', '2020-09-17', '2020-09-18',
               '2020-09-21', '2020-09-22', '2020-09-23', '2020-09-24',
               '2020-09-25', '2020-09-28', '2020-09-29', '2020-09-30'],
              dtype='datetime64[ns]', freq='B')

However, this returns all the business days. I want to return all the Tue, Wed, Thur, Fri and Sat days instead. Perhaps this can be done with some kind of custom set up or some kind of offset? Specifically, is there a way to do it directly using the date_range functionality and the freq input? If not, how can this be achieved the most simply?

Thanks!

2 Answers

With dayofweek

idx = pd.date_range(start=dt.datetime(2020,8,28),end=dt.datetime(2020,9,30))
s = idx.dayofweek
idx[s.isin([2,3,4,5])]

DatetimeIndex(['2020-08-28', '2020-08-29', '2020-09-02', '2020-09-03',
           '2020-09-04', '2020-09-05', '2020-09-09', '2020-09-10',
           '2020-09-11', '2020-09-12', '2020-09-16', '2020-09-17',
           '2020-09-18', '2020-09-19', '2020-09-23', '2020-09-24',
           '2020-09-25', '2020-09-26', '2020-09-30'],
          dtype='datetime64[ns]', freq=None)

you can just add a day with Timedelta, but to not change the daterange you want, you need to remove a day when creating the boundaries.

(pd.date_range(start=dt.datetime(2020,8,27),end=dt.datetime(2020,9,29),freq='B') 
  + pd.Timedelta(days=1))

DatetimeIndex(['2020-08-28', '2020-08-29', '2020-09-01', '2020-09-02',
               '2020-09-03', '2020-09-04', '2020-09-05', '2020-09-08',
               '2020-09-09', '2020-09-10', '2020-09-11', '2020-09-12',
               '2020-09-15', '2020-09-16', '2020-09-17', '2020-09-18',
               '2020-09-19', '2020-09-22', '2020-09-23', '2020-09-24',
               '2020-09-25', '2020-09-26', '2020-09-29', '2020-09-30'],
              dtype='datetime64[ns]', freq=None)

EDIT: you can also define your CustomBusinessDay

cbd = pd.tseries.offsets.CustomBusinessDay(weekmask='Tue Wed Thu Fri Sat')
pd.date_range(start=dt.datetime(2020,8,28),end=dt.datetime(2020,9,30),freq=cbd)
Related