Skip to content Skip to sidebar Skip to footer

How To Add Business Days In Date Excluding Holidays

I have a dataframe (df) with start_date column's and add_days column's (=10). I want to create target_date (=start_date + add_days) excluding week-end and holidays (holidays as dat

Solution 1:

The comments by ALollz are very valid; customizing your date during creation to only keep what is defined as business day for your problem would be optimal.

However, I assume that you cannot define the business day beforehand and that you need to solve the problem with the data frame constructed as is.

Here is one possible solution:

import pandas as pd
import numpy as np
from datetime import timedelta

# Goal is to offset a start date by N business days (weekday + not a holiday)# Here we fake the dataset as it was not provided
num_row = 1000
df = pd.DataFrame()
df['start_date'] = pd.date_range(start='1/1/1979', periods=num_row, freq='D')
df['add_days'] = pd.Series([10]*num_row)

# Define what is a week day
week_day = [0,1,2,3,4] # Monday to Friday# Define what is a holiday with month and day without year (you can add more)
holidays = ['10-30','12-24'] 

defadd_days_to_business_day(df, week_day, holidays, increment=10):
    '''
       modify the dataframe to increment only the days that are part of a weekday
       and not part of a pre-defined holiday
       >>> add_days_to_business_day(df, [0,1,2,3,4], ['10-31','12-31'])
           this will increment by 10 the days from Monday to Friday excluding Halloween and new year-eve
    '''# Increment everything that is in a business day
    df.loc[df['start_date'].dt.dayofweek.isin(week_day),'target_date'] = df['start_date'] + timedelta(days=increment)
    # Remove every increment done on a holiday
    df.loc[df['start_date'].dt.strftime('%m-%d').isin(holidays), 'target_date'] = np.datetime64('NaT')


add_days_to_business_day(df, week_day, holidays)
df

To Note: I'm not using the 'add_days' column since its just a repeated value. I am instead using a parameter for my function increment which will increment by N number of days (with a default of N = 10).

Hope it helps!

Post a Comment for "How To Add Business Days In Date Excluding Holidays"