Get the Most recent previous business day using Python


In today's fast-paced based business environment and with a huge amount of work going on around the world, developers need to analyze the dates accurately up to date. The business days are different from normal days. Business days are different from normal days. Typically the days on which office works run, like the stock market, government officials, schools, offices, banks, etc. While dealing with real-world problems involving such institutions, developers must design the systems as per the business days. This article will explain how to get the most recent business day in Python.

Use The date time Library

The date time is a popular Python library that lets us deal with dates, times, timestamps, etc. It allows us to manipulate, format, and perform several calculations and operations on the dates. The library provides us with multiple classes like date time, date, time, time delta to deal with different types of operations. We can use the "today" date time method to access the current date. Since typically there are five business days a week, we can write the program to access only the previous day, which comes under the category of business days.

Syntax

timedelta(days = <number of days>)

time delta here is the class provided by the time delta module. It represents the difference between two dates or times. days parameter takes the number of days in integer as the duration of the days by which we need to have a difference of the dates.

Example

We first imported the date time and the time delta classes in the following example. We defined the get_previous_day function, which calculates the previous business day based on the current date. The "today" method retrieves the current date; the time delta method returns the previous day delayed by the parameters passed. We passed the parameter to be 1, which means we want the previous day. Using the while statement, we only accepted the day, which also falls under the category of the business day. We returned the previous business day in a year month- date format using the “start time” method.

from datetime import datetime, timedelta
def get_previous_business_day():
    today = datetime.today()
    one_day = timedelta(days=1)
    previous_day = today - one_day
    while previous_day.weekday() >= 5: 
        previous_day -= one_day
    return previous_day.strftime("%Y-%m-%d")
print(f"The previous business day is: {get_previous_business_day()}")

Output

The previous business day is: 2023-05-26

Use Date Offset Of Pandas Library

Pandas is a popular data analysis library in Python. It also offers a convenient way to deal with the time. Pandas' Timestamp method can convert the date into a Timestamp object—the pd.t series.The offsets module within Pandas provides the Business Day class, representing a single business day. By specifying the n parameter with a value of 1, you can create a Business Day object representing one business day.

Syntax

pd.DateOffset(days=<number of days>)

The Data Offset class takes the number of days as the required parameter. It represents the time offset representing a specific number of days. The Date Offset object allows you to perform date arithmetic by adding or subtracting a specific number of days and other time components if needed.

Example code

We used the Pandas library in the following code to get the previous business day. We created the function named get_previous_business_day. Under this function, We used the today method to get the current date. We used the Date Offset to shift the dates. We used the b date_range method and periods=1 parameter to specify that we want the previous business day.

import pandas as pd
def get_previous_business_day():
    today = pd.Timestamp.today()
    previous_day = today - pd.DateOffset(days=1)
    previous_business_day = pd.bdate_range(end=previous_day, periods=1)[0]
    return previous_business_day.strftime("%Y-%m-%d")
print(f"The previous business day is: {get_previous_business_day()}")

Output

The previous business day is: 2023-05-26

Use The Business Day Method Of Pandas Library

The Business Day method in Panda's library is a powerful tool for handling business days and working with custom calendars. You must create a "Business Day" object first; each date under this method represents a business day (excluding the weekends).

Syntax

pd.tseries.offsets.BusinessDay(<number of days>)

The function defines a time offset which represents a single business day. the function takes care of the weekends (Saturday and Sunday). The function takes the number of days as the parameter under the business days category

Example

In the following example, we have specified the date '2023-05-28'. We need to calculate the previous business day before this date. We called the get_previous_business_day function with the date_to-offset as the parameter. Under the function, we have used the Business Day method only to delay the date concerning business days. Note that we do not need to write some code for the business day explicitly. The method takes care of

import pandas as pd
def get_previous_business_day(date):
    previous_business_day = date - pd.tseries.offsets.BusinessDay(1)
    return previous_business_day
date_to_offset = pd.Timestamp('2023-05-28')
previous_business_day = get_previous_business_day(date_to_offset)
print(f"The previous business day is: {previous_business_day}")

Output

The previous business day is − 2023-05-26

Conclusion

In this article, we understood how to get the most recent business day using Python. Python offers several libraries and modules to deal with business days. We can use the date time, pandas, etc., to deal with the business days. All these libraries have built-in functions enabling developers to access the business days. However, one should also know that business days are flexible throughout the year. There can be occasional holidays, so developers may need to use some third-party API keys or align the codes with the real-time data.

Updated on: 28-Jul-2023

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements