Python Pandas CustomBusinessHour – 只有不在偏移处时才将提供的日期向前滚动到下一个偏移
要只有在不在偏移位置时才将提供的日期向前滚动到下一个偏移,请使用Pandas中的CustomBusinessHour.rollforward()方法。
首先,导入所需的库−
import pandas as pd
在Pandas中设置时间戳对象−
timestamp = pd.Timestamp('2021-12-20 08:35:10')
创建CustomBusinessHour Offset。 CustomBusinessHour是DateOffset子类。有效工作日的周掩码−
cbhOffset = pd.tseries.offsets.CustomBusinessHour(n = 5, weekmask = 'Mon Tue Wed Fri')
将偏移添加到时间戳并显示更新的时间戳−
print("\n更新时间戳...\n",timestamp + cbhOffset)
如果不处于偏移处,请向前滚动−
roll = cbhOffset.rollforward(pd.Timestamp('2021-12-30 08:35:10'))
显示结果 −
print("\n向前滚动结果...\n",roll)
示例
以下是代码−
import pandas as pd
# 在Pandas中设置时间戳对象
timestamp = pd.Timestamp('2021-12-20 08:35:10')
# 显示时间戳
print("时间戳...\n",timestamp)
# 创建CustomBusinessHour Offset
# CustomBusinessHour是DateOffset子类
# 有效工作日的周掩码
cbhOffset = pd.tseries.offsets.CustomBusinessHour(n = 5, weekmask = 'Mon Tue Wed Fri')
# 显示CustomBusinessHour Offset
print("\nCustomBusinessHour Offset...\n",cbhOffset)
# 将偏移添加到时间戳并显示更新的时间戳
print("\n更新时间戳...\n",timestamp + cbhOffset)
# 如果不在偏移处,则向前滚动
roll = cbhOffset.rollforward(pd.Timestamp('2021-12-30 08:35:10'))
# 显示结果
print("\n向前滚动结果...\n",roll)
输出
这将产生以下代码−
时间戳...
2021-12-20 08:35:10
CustomBusinessHour Offset...
<5 * CustomBusinessHours: CBH=09:00-17:00>
更新时间戳...
2021-12-20 14:00:00
向前滚动结果...
2021-12-31 09:00:00
极客教程