Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get the Most recent previous business day using Python
In business applications, developers often need to calculate the most recent business day (excluding weekends). This is crucial for financial systems, reporting tools, and data analysis where operations only occur on weekdays.
Using the datetime Library
The datetime library provides built-in classes to handle dates and times. We can use timedelta to subtract days and check if the result is a business day using the weekday() method.
Syntax
timedelta(days=<number of days>)
The timedelta class represents the difference between two dates. The days parameter specifies how many days to add or subtract.
Example
This function finds the previous business day by going back one day at a time until it finds a weekday (Monday=0 to Friday=4) ?
from datetime import datetime, timedelta
def get_previous_business_day():
today = datetime.today()
previous_day = today - timedelta(days=1)
# Keep going back until we find a business day (weekday < 5)
while previous_day.weekday() >= 5: # 5=Saturday, 6=Sunday
previous_day -= timedelta(days=1)
return previous_day.strftime("%Y-%m-%d")
print(f"The previous business day is: {get_previous_business_day()}")
The previous business day is: 2023-05-26
Using Pandas DateOffset
Pandas provides DateOffset for date arithmetic and bdate_range to generate business day sequences efficiently ?
Syntax
pd.DateOffset(days=<number of days>) pd.bdate_range(end=date, periods=1)
Example
import pandas as pd
def get_previous_business_day():
today = pd.Timestamp.today()
previous_day = today - pd.DateOffset(days=1)
# Get the most recent business day on or before previous_day
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()}")
The previous business day is: 2023-05-26
Using BusinessDay Offset
The BusinessDay offset automatically handles weekends and provides the cleanest solution ?
Syntax
pd.tseries.offsets.BusinessDay(<number of days>)
Example
import pandas as pd
def get_previous_business_day(date):
return date - pd.tseries.offsets.BusinessDay(1)
# Example with a specific date (Sunday)
date_to_offset = pd.Timestamp('2023-05-28') # This is a Sunday
previous_business_day = get_previous_business_day(date_to_offset)
print(f"The previous business day is: {previous_business_day.strftime('%Y-%m-%d')}")
The previous business day is: 2023-05-26
Comparison
| Method | Pros | Cons |
|---|---|---|
datetime + timedelta |
No external dependencies | Manual weekend checking |
pandas DateOffset |
Built-in business day support | Requires pandas |
BusinessDay offset |
Most concise and clear | Requires pandas |
Conclusion
Use BusinessDay offset for the cleanest solution when pandas is available. For pure Python, use datetime with a weekend-checking loop. All methods handle weekends automatically but may need customization for holidays.
