Pandas Filter dataframe according to working days

Viewed 80

I want to filter a df with respect to working days.The df is:

name     date
aaa    12/06/2021
bbb    11/06/2021
ccc    10/06/2021
zzz    15/06/2021
ddd    13/06/2021
eee    10/05/2021
fff    01/06/2021
ggg    10/05/2021
hhh    13/06/2021
iii    14/06/2021
nnn    15/06/2021
jjj    15/06/2021

Now for everday process i want all the rows before two working days that means 13/06/2021 will not be included as it was a Sunday.I used

new_date = dt.date.today()-pd.Timedelta(2, unit='d')
new_date = pd.to_datetime(new_date)
new_df = df[df['date'] < new_date]

Output should be

name     date
aaa    12/06/2021
bbb    11/06/2021
ccc    10/06/2021
eee    10/05/2021
fff    01/06/2021
ggg    10/05/2021

but it is giving me sunday also ie 13/06/2021.Can anyone help me out here please

1 Answers

If need exlude only Sundays use offsets.CustomBusinessDay:

df['date'] = pd.to_datetime(df['date'], dayfirst=True)

offset = pd.offsets.CustomBusinessDay(2, weekmask='Mon Tue Wed Thu Fri Sat')
new_date = pd.to_datetime('today').normalize() - offset
print (new_date)
2021-06-12 00:00:00

new_df = df[df['date'] <= new_date]
print (new_df)
  name       date
0  aaa 2021-06-12
1  bbb 2021-06-11
2  ccc 2021-06-10
5  eee 2021-05-10
6  fff 2021-06-01
7  ggg 2021-05-10
Related