Python Pandas CustomBusinessHour - 检查给定的时间戳是否在偏移量上

pythonserver side programmingprogramming更新于 2026/1/29 9:16:17

要检查给定的时间戳是否在偏移量上,请使用 Pandas 中的 CustomBusinessHour.is_on_offset()。将时间戳作为参数传递以进行检查。

首先,导入所需的库 −

import pandas as pd

在 Pandas 中设置时间戳对象 −

timestamp = pd.Timestamp('2021-11-14 05:20:30')

创建 CustomBusinessHour 偏移量。 CustomBusinessHour 是 DateOffset 的子类 −

cbhOffset = pd.tseries.offsets.CustomBusinessHour(start="09:30", end = "18:30")

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

print("\n更新时间戳...\n",timestamp + cbhOffset)

检查给定的时间戳是否在偏移量 −

offset = cbhOffset.is_on_offset(pd.Timestamp('2021-11-20 05:20:30'))

显示结果 −

print("\n检查给定的时间戳是否在偏移量上...\n",offset)

示例

以下是代码 −

import pandas as pd

# 在 Pandas 中设置时间戳对象
timestamp = pd.Timestamp('2021-11-14 05:20:30')

# 显示时间戳
print("时间戳...\n",timestamp)
# 创建 CustomBusinessHour 偏移量
# CustomBusinessHour 是 DateOffset 子类
# 此处"start" 为自定义营业时间的开始时间,24 小时制。
# "end" 为自定义营业时间的结束时间,24 小时制。
cbhOffset = pd.tseries.offsets.CustomBusinessHour(start="09:30", end = "18:30")

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

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

# 检查给定的时间戳是否在偏移量上
offset = cbhOffset.is_on_offset(pd.Timestamp('2021-11-20 05:20:30'))

# 显示结果
print("\n检查给定的时间戳是否在偏移量上...\n",offset)

输出

这将产生以下代码 −

时间戳...
2021-11-14 05:20:30

CustomBusinessHour 偏移量...
<CustomBusinessHour: CBH=09:30-18:30>

更新时间戳...
2021-11-15 10:30:00

检查给定的时间戳是否偏移...
False

相关文章


有用资源