Add n business days to a given date ignoring holidays and weekends in python

When working with dates in Python, it is often necessary to add a certain number of business days to a given date. However, it is important to exclude weekends and holidays from the calculation. In this article, we will explore three different ways to solve this problem using Python.

Solution 1: Using the datetime and timedelta modules

from datetime import datetime, timedelta

def add_business_days(start_date, num_days):
    current_date = start_date
    while num_days > 0:
        current_date += timedelta(days=1)
        if current_date.weekday() < 5:  # Exclude weekends
            num_days -= 1
    return current_date

start_date = datetime(2022, 1, 1)
num_days = 5
result = add_business_days(start_date, num_days)
print(result)

In this solution, we use the datetime module to represent dates and the timedelta module to perform date arithmetic. We start by defining a function called add_business_days that takes a start_date and the number of days to add. We initialize a current_date variable with the start_date and iterate until we have added the desired number of business days. Inside the loop, we increment the current_date by one day and check if it is a weekday (Monday to Friday). If it is, we decrement the num_days counter. Finally, we return the resulting date.

Solution 2: Using the pandas library

import pandas as pd

def add_business_days(start_date, num_days):
    current_date = pd.to_datetime(start_date)
    while num_days > 0:
        current_date += pd.DateOffset(days=1)
        if current_date.weekday() < 5:  # Exclude weekends
            num_days -= 1
    return current_date

start_date = '2022-01-01'
num_days = 5
result = add_business_days(start_date, num_days)
print(result)

In this solution, we leverage the power of the pandas library, which provides extensive functionality for working with dates and times. We define a function called add_business_days that takes a start_date and the number of days to add. We convert the start_date to a pandas datetime object using the pd.to_datetime function. Then, we iterate until we have added the desired number of business days, incrementing the current_date by one day at each iteration. We also exclude weekends by checking the weekday attribute of the current_date. Finally, we return the resulting date.

Solution 3: Using the dateutil library

from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, DAILY

def add_business_days(start_date, num_days):
    current_date = datetime.strptime(start_date, '%Y-%m-%d')
    business_days = list(rrule(DAILY, dtstart=current_date, byweekday=(0, 1, 2, 3, 4)))
    result_date = business_days[num_days - 1]
    return result_date.strftime('%Y-%m-%d')

start_date = '2022-01-01'
num_days = 5
result = add_business_days(start_date, num_days)
print(result)

In this solution, we utilize the dateutil library, which provides powerful date and time manipulation capabilities. We define a function called add_business_days that takes a start_date and the number of days to add. We convert the start_date to a datetime object using the datetime.strptime function. Then, we generate a list of business days using the rrule function from the dateutil.rrule module, specifying the start_date and the byweekday parameter to exclude weekends. Finally, we return the desired business day by indexing the business_days list and converting it back to a string format.

After exploring these three solutions, it is clear that Solution 2, which utilizes the pandas library, is the most concise and efficient option. Pandas provides a high-level interface for working with dates and times, making it easier to handle business day calculations. Additionally, pandas offers various advanced features and optimizations, making it a powerful tool for date manipulation tasks.

Rate this post

6 Responses

  1. Solution 3 with the dateutil library seems like a smart choice. Who needs weekends and holidays anyway? 🤷‍♀️

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents