Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas: Tạo BusinessHour offset

Để tạo một BusinessHour offset trong Pandas, sử dụng phương thức pd.tseries.offsets.BusinessHour(). Offset này cho phép định nghĩa giờ làm việc tùy chỉnh và thực hiện phép toán ngày giờ chỉ tính trong khung giờ làm việc.

Cú pháp cơ bản

pd.tseries.offsets.BusinessHour(start="09:00", end="17:00", n=1, offset=timedelta(0))
Tham số Mô tả
start Giờ bắt đầu làm việc (định dạng 24h, mặc định "09:00")
end Giờ kết thúc làm việc (định dạng 24h, mặc định "17:00")
n Số lần lặp offset (mặc định 1)
offset Timedelta bổ sung (mặc định 0)
normalize Chuẩn hóa về 00:00:00 (mặc định False)

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo BusinessHour Offset

bhOffset = pd.tseries.offsets.BusinessHour(start="09:30", end="18:00")

3. Thiết lập timestamp

timestamp = pd.Timestamp('2021-1-1 01:55:30')

4. Cộng offset vào timestamp

print("\nUpdated Timestamp...\n", timestamp + bhOffset)

Ví dụ hoàn chỉnh

import pandas as pd

timestamp = pd.Timestamp('2021-1-1 01:55:30')
print("Timestamp...\n", timestamp)

# Tạo BusinessHour: 09:30 - 18:00
bhOffset = pd.tseries.offsets.BusinessHour(start="09:30", end="18:00")
print("\nBusinessHour Offset...\n", bhOffset)

# Cộng offset: timestamp 01:55 -> nhảy đến 09:30 cùng ngày
print("\nUpdated Timestamp...\n", timestamp + bhOffset)

Kết quả đầu ra

Timestamp...
2021-01-01 01:55:30
BusinessHour Offset...
<BusinessHour: BH=09:30-18:00>
Updated Timestamp...
2021-01-01 10:30:00

Giải thích: Timestamp ban đầu là 01:55 (ngoài giờ làm việc). Khi cộng 1 BusinessHour, nó nhảy đến giờ mở cửa 09:30 và cộng thêm 1 giờ làm việc → 10:30. Nếu timestamp đã trong giờ làm việc, nó sẽ cộng trực tiếp.

Ví dụ nâng cao

# 2 giờ làm việc từ 09:00-17:00
bh2 = pd.tseries.offsets.BusinessHour(n=2)
print(timestamp + bh2)  # 2021-01-01 11:00:00

# Với offset bổ sung 30 phút
bh3 = pd.tseries.offsets.BusinessHour(start="09:00", end="17:00", offset=pd.Timedelta(minutes=30))
print(timestamp + bh3)  # 2021-01-01 10:00:00