Home > Software engineering >  How to find the business day of the previous year (or closest of the week before if weekend)
How to find the business day of the previous year (or closest of the week before if weekend)

Time:06-29

I'm trying to find previous year business day. If the day falls on a weekend, I want the last valid business day.

Below is my sample code:

import pandas as pd
import numpy as np
from datetime import datetime as dt
from pandas.tseries.offsets import BDay

df = pd.DataFrame({'Date':['20210625','20220626'],'Amount':[10,20]})
df['Date'] = pd.to_datetime(df['Date'],infer_datetime_format=True)
date_1 = df['Date'].iloc[-1]
date_2 = date_1 - pd.DateOffset(years=1)
df_2 = df[df['Date'] == date_2]
df_2

So what I need is that how to find date_2 as the recent business date of the same date of last year. In this case, the expected output would be 2021-06-25 (Fri) -> 2020-06-25 (Thu) and 2022-06-26 (Sun) -> 2021-06-25 (Fri).

Thank you.

CodePudding user response:

The question is a bit unclear, I'll answer the How to find the "recent business date of the same date of last year" part:

from pandas.tseries.offsets import BDay

df['lastYear'] = df['Date']-pd.DateOffset(years=1) 0*BDay()

output:

        Date  Amount   lastYear
0 2021-06-25      10 2020-06-25
1 2022-06-26      20 2021-06-28

previous BDay if not a BDay:

from pandas.tseries.offsets import BDay

df['lastYear'] = df['Date']-BDay(1)-pd.DateOffset(years=1) BDay(1)

output (with more examples):

        Date  Amount   lastYear
0 2021-06-25      10 2020-06-25
1 2022-06-24      20 2021-06-24
2 2022-06-25      30 2021-06-25
3 2022-06-26      40 2021-06-25
4 2022-06-27      50 2021-06-25
5 2022-06-28      60 2021-06-28
  • Related