Pandas:计算时间戳和当前时间之间经过的时间,但只计算营业时间和时区
我正在尝试使用 Pandas 来计算经过的业务秒数。我在 Pandas 数据框中有一列,它在纽约时区有一堆时间戳。这是我到目前为止的代码:
import pandas as pd
import datetime
times = pd.DataFrame([datetime.datetime.now(timezone('America/New_York')),datetime.datetime.now(timezone('America/New_York'))],columns=['timestamp'])
time.sleep(2)
times['difference'] = (datetime.datetime.now(timezone('America/New_York')) - times)
times['difference'] = times['difference'].dt.seconds
这按预期工作,并在“差异”列中给出答案为 2。但现在我只想包括营业时间(比如上午 9 点到下午 5 点)。所以昨天下午 5 点到今天早上 9 点之间的输出为零。我已经阅读了关于时间偏移的 Pandas 文档并寻找了类似的问题,但没有找到任何有效的例子。
回答
您可以通过首先使用 Pandas BusinessHour 类检查给定时间戳是否在营业时间内(感谢此线程),然后计算时差或在时间戳不在营业时间时分配零来实现此目的。
我创建了一个虚拟数据集来测试代码,如下所示:
import pandas as pd
import time
# Sets the timezone
timezone = "America/New_York"
# Gets business hours from native Pandas class
biz_hours = pd.offsets.BusinessHour()
# Creates array with timestamps to test code
times_array = pd.date_range(start='2021-05-18 16:59:00', end='2021-05-18 17:01:00',
tz=timezone, freq='S')
# Creates DataFrame with timestamps
times = pd.DataFrame(times_array,columns=['timestamp'])
# Checks if a timestamp falls within business hours
times['is_biz_hour'] = times['timestamp'].apply(pd.Timestamp).apply(biz_hours.onOffset)
time.sleep(2)
# Calculates the time delta or assign zero, as per business hour condition
times['difference'] = (times.apply(lambda x: (pd.Timestamp.now(tz=timezone) - x['timestamp']).seconds
if x['is_biz_hour'] else 0,
axis=1))
目前的输出并不完美,因为它从现在的时间中减去了时间戳,从而产生了很大的差异:
timestamp is_biz_hour difference
57 2021-05-18 16:59:57-04:00 True 71238
58 2021-05-18 16:59:58-04:00 True 71237
59 2021-05-18 16:59:59-04:00 True 71236
60 2021-05-18 17:00:00-04:00 True 71235
61 2021-05-18 17:00:01-04:00 False 0
62 2021-05-18 17:00:02-04:00 False 0
63 2021-05-18 17:00:03-04:00 False 0
64 2021-05-18 17:00:04-04:00 False 0
但是,您可以看到下午 5 点之后的时间戳差异为 0,而其他时间戳具有有效差异。