Python Pandas CustomBusinessHour——檢查給定的時間戳是否為偏移量


要檢查給定的時間戳是否為偏移量,請在 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("\nUpdated Timestamp...\n",timestamp + cbhOffset)

檢查給定的時間戳是否為偏移量 −

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

顯示結果 −

print("\nCheck if the given timestamp is on offset or not...\n",offset)

示例

以下是程式碼 −

import pandas as pd

# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-11-14 05:20:30')

# Display the Timestamp
print("Timestamp...\n",timestamp)
# Create the CustomBusinessHour Offset
# CustomBusinessHour is the DateOffset subclass
# Here, "start" is the start time of your custom business hour in 24h format.
# The "end" is the end time of your custom business hour in 24h format.
cbhOffset = pd.tseries.offsets.CustomBusinessHour(start="09:30", end = "18:30")

# Display the CustomBusinessHour Offset
print("\nCustomBusinessHour Offset...\n",cbhOffset)

# Add the offset to the Timestamp and display the Updated Timestamp
print("\nUpdated Timestamp...\n",timestamp + cbhOffset)

# Check if the given timestamp is on offset or not
offset = cbhOffset.is_on_offset(pd.Timestamp('2021-11-20 05:20:30'))

# display the result
print("\nCheck if the given timestamp is on offset or not...\n",offset)

輸出

這將生成以下程式碼 −

Timestamp...
 2021-11-14 05:20:30

CustomBusinessHour Offset...
 <CustomBusinessHour: CBH=09:30-18:30>

Updated Timestamp...
 2021-11-15 10:30:00

Check if the given timestamp is on offset or not...
 False

更新於:2021-10-22

205 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始操作
廣告