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
Selected Reading
Python Pandas - Create a BusinessHour offset
To create a BusinessHour offset, use the pd.tseries.offsets.BusinessHour() method in Pandas. This offset allows you to work with business hours and automatically handles time calculations within specified working hours.
Syntax
pd.tseries.offsets.BusinessHour(start="09:00", end="17:00")
Parameters
The BusinessHour offset accepts the following key parameters ?
- start ? Start time of business hours in 24-hour format (default: "09:00")
- end ? End time of business hours in 24-hour format (default: "17:00")
- n ? Number of business hours to offset (default: 1)
Example
Let's create a BusinessHour offset and apply it to a timestamp ?
import pandas as pd
# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-1-1 01:55:30')
# Display the original Timestamp
print("Original Timestamp:")
print(timestamp)
# Create the BusinessHour Offset
# BusinessHour is the DateOffset subclass
# Here, "start" is the start time of your custom business hour in 24h format
# The "end" is the end time of your custom business hour in 24h format
bhOffset = pd.tseries.offsets.BusinessHour(start="09:30", end="18:00")
# Display the BusinessHour Offset
print("\nBusinessHour Offset:")
print(bhOffset)
# Add the offset to the Timestamp and display the Updated Timestamp
print("\nUpdated Timestamp:")
print(timestamp + bhOffset)
Original Timestamp: 2021-01-01 01:55:30 BusinessHour Offset: <BusinessHour: BH=09:30-18:00> Updated Timestamp: 2021-01-01 10:30:00
Multiple Business Hours
You can also add multiple business hours by specifying the n parameter ?
import pandas as pd
timestamp = pd.Timestamp('2021-1-1 14:30:00')
print("Original Timestamp:")
print(timestamp)
# Create offset for 3 business hours
bhOffset = pd.tseries.offsets.BusinessHour(n=3, start="09:00", end="17:00")
print("\nAdding 3 Business Hours:")
print(timestamp + bhOffset)
Original Timestamp: 2021-01-01 14:30:00 Adding 3 Business Hours: 2021-01-04 09:30:00
How It Works
The BusinessHour offset automatically handles several scenarios ?
- If the timestamp is outside business hours, it moves to the next business hour start
- If adding hours would exceed the business day, it carries over to the next business day
- Weekends are automatically skipped
Conclusion
The BusinessHour offset is useful for financial and business applications where calculations must respect working hours. It automatically handles time boundaries and weekend transitions.
Advertisements
