Guey
Guey

Reputation: 73

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 dataframe).

I do some research and I try this.

from datetime import date,  timedelta
import datetime as dt

df["star_date"] = pd.to_datetime(df["star_date"])
Holidays['Date_holi'] = pd.to_datetime(Holidays['Date_holi'])


def date_by_adding_business_days(from_date, add_days, holidays):
    business_days_to_add = add_days
    current_date = from_date
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5: # sunday = 6
            continue
        if current_date in holidays:
            continue
        business_days_to_add -= 1
    return current_date


#demo:
base["Target_date"]=date_by_adding_business_days(df["start_date"], 10, Holidays['Date_holi'])

but i get this error:

AttributeError: 'Series' object has no attribute 'weekday'

Thanks you for your help.

Upvotes: 4

Views: 2820

Answers (1)

Yacine Mahdid
Yacine Mahdid

Reputation: 731

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'] 

def add_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!

Upvotes: 1

Related Questions