Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find business date of last year

I’m trying to find last year business date based on df last row but I have a problem that my datatable just has data on business date. So if last year date was weekend, nothing shows.

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. For example in this case is 2021-06-25.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading