gpt4 book ai didi

python - Pandas :计算时间戳和当前时间之间耗时,但仅限营业时间和时区

转载 作者:行者123 更新时间:2023-12-02 16:12:01 25 4
gpt4 key购买 nike

我正在尝试使用 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 this thread 检查给定时间戳是否在工作时间内(感谢 BusinessHour class)来实现此目的然后计算时间差,如果时间戳不在工作时间,则分配零。

我创建了一个虚拟数据集来测试代码,如下所示:

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,而其他差异有效。

关于python - Pandas :计算时间戳和当前时间之间耗时,但仅限营业时间和时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67742508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com