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

Python Pandas: Di chuyển đến ngày làm việc tiếp theo với BusinessHour.next_bday

Trong Pandas, thuộc tính BusinessHour.next_bday cho phép bạn nhanh chóng chuyển đến ngày làm việc tiếp theo. Điều này rất hữu ích khi xử lý dữ liệu tài chính hoặc lịch trình kinh doanh.

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

1. Import thư viện cần thiết

import datetime
import pandas as pd

2. Tạo đối tượng BusinessHour Offset

BusinessHour là lớp con của DateOffset. Ví dụ dưới đây tạo offset 3 ngày và 3 giờ:

bhOffset = pd.tseries.offsets.BusinessHour(offset=datetime.timedelta(days=3, hours=3))

3. Hiển thị BusinessHour Offset

print("\nBusinessHour Offset...\n", bhOffset)

4. Thiết lập timestamp

timestamp = pd.Timestamp('2021-9-30 06:50:20')

5. Lấy ngày làm việc tiếp theo

print("\nNgày làm việc tiếp theo...\n", timestamp + bhOffset.next_bday)

Ví dụ hoàn chỉnh

import datetime
import pandas as pd

# Thiết lập timestamp
timestamp = pd.Timestamp('2021-9-30 06:50:20')
print("Timestamp...\n", timestamp)

# Tạo BusinessHour Offset
bhOffset = pd.tseries.offsets.BusinessHour(offset=datetime.timedelta(days=3, hours=3))
print("\nBusinessHour Offset...\n", bhOffset)

# Hiển thị ngày làm việc tiếp theo
print("\nNgày làm việc tiếp theo...\n", timestamp + bhOffset.next_bday)

Kết quả đầu ra

Timestamp...
2021-09-30 06:50:20
BusinessHour Offset...
<BusinessHour: offset=datetime.timedelta(days=3, seconds=10800): BH=09:00-17:00>
Ngày làm việc tiếp theo...
2021-10-01 06:50:20

Lưu ý: Kết quả cho thấy từ thứ Năm (30/9) nhảy sang thứ Sáu (1/10), bỏ qua cuối tuần. Thuộc tính next_bday tự động xử lý logic ngày làm việc.