Python Pandas CustomBusinessHour - 将提供的日期向后滚动

pythonserver side programmingprogramming更新于 2026/1/29 3:24:17

要将提供的日期向后滚动,请使用 Pandas 中的 CustomBusinessHour.rollback() 方法。首先,导入所需的库 −

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("\n更新时间戳...\n",timestamp + cbhOffset)

如果不在偏移量 − 上,则向后滚动

roll_back = cbhOffset.rollback(pd.Timestamp('2021-12-18 08:35:10'))

显示结果 −

print("\nRoll Backward Result...\n",roll_back)

示例

以下是代码 −

import pandas as pd

# 在 Pandas 中设置时间戳对象
timestamp = pd.Timestamp('2021-12-20 08:35:10')

# 显示时间戳
print("时间戳...\n",timestamp)

# 创建 CustomBusinessHour 偏移量
# CustomBusinessHour 是 DateOffset 子类
# 有效工作日的 Weekmask
cbhOffset = pd.tseries.offsets.CustomBusinessHour(n = 5, weekmask = 'Mon Tue Wed Fri')

# 显示 CustomBusinessHour 偏移量
print("\nCustomBusinessHour 偏移量...\n",cbhOffset)

# 将偏移量添加到时间戳并显示更新时间戳
print("\n更新时间戳...\n",timestamp + cbhOffset)

# 如果不在偏移量上,则向后滚动
roll_back = cbhOffset.rollback(pd.Timestamp('2021-12-18 08:35:10'))

# 显示结果
print("\n向后滚动结果...\n",roll_back)

输出

这将产生以下代码 −

时间戳...
2021-12-20 08:35:10

CustomBusinessHour 偏移量...
<5 * CustomBusinessHours: CBH=09:00-17:00>

更新时间戳...
2021-12-20 14:00:00

向后滚动结果...
2021-12-17 17:00:00

相关文章


有用资源