首页 文章资讯内容详情

Python Pandas CustomBusinessHour - 仅当不在偏移量时才将提供的日期向前滚动到下一个偏移量

2026-06-03 1 花语

要将提供的日期前滚到下一个偏移量(如果不在偏移量上),请使用Pandas中的方法。CustomBusinessHour.rollforward()

首先,导入所需的库-

import pandas as pd

在Pandas中设置时间戳对象-

timestamp = pd.Timestamp(2021-12-20 08:35:10)

创建CustomBusinessHour偏移量。CustomBusinessHour是DateOffset子类。有效工作日的周掩码-

cbhOffset = pd.tseries.offsets.CustomBusinessHour(n = 5, weekmask = Mon Tue Wed Fri)

将偏移量添加到时间戳并显示更新的时间戳-

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

如果不在偏移上,则向前滚动-

roll = cbhOffset.rollforward(pd.Timestamp(2021-12-30 08:35:10))

显示结果-

print("\nRoll forward Result...\n",roll)

示例

以下是代码-

import pandas as pd #SetthetimestampobjectinPandas timestamp = pd.Timestamp(2021-12-20 08:35:10) #DisplaytheTimestamp print("Timestamp...\n",timestamp) #CreatetheCustomBusinessHourOffset #CustomBusinessHouristheDateOffsetsubclass #Weekmaskofvalidbusinessdays cbhOffset = pd.tseries.offsets.CustomBusinessHour(n = 5, weekmask = Mon Tue Wed Fri) #DisplaytheCustomBusinessHourOffset print("\nCustomBusinessHour Offset...\n",cbhOffset) #AddtheoffsettotheTimestampanddisplaytheUpdatedTimestamp print("\nUpdated Timestamp...\n",timestamp + cbhOffset) #rollforwardifnotonoffset roll = cbhOffset.rollforward(pd.Timestamp(2021-12-30 08:35:10)) #displaytheresult print("\nRoll forward Result...\n",roll)输出结果

这将产生以下代码-

Timestamp... 2021-12-20 08:35:10 CustomBusinessHour Offset... <5 * CustomBusinessHours: CBH=09:00-17:00> Updated Timestamp... 2021-12-20 14:00:00 Roll forward Result... 2021-12-31 09:00:00