查找每个 30 分钟间隔中有多少个事件,而无需对事件循环多次

问题描述 投票:0回答:1

这可以工作并打印每 30 分钟间隔内的事件数:

00:00至00:30、00:30至01:00、...、23:30至24:00

import time, datetime
L = ["20231017_021000", "20231017_021100", "20231017_021200", "20231017_052800", "20231017_093100", "20231017_093900"]
d = datetime.datetime.strptime("20231017_000000", "%Y%m%d_%H%M%S")
M = [(d + datetime.timedelta(minutes=30*k)).strftime("%Y%m%d_%H%M%S") for k in range(49)]
Y = [sum([m1 < l <= m2 for l in L]) for m1, m2 in zip(M, M[1:])]
print(Y)
# [0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# => 3 events between 02:00 and 02:30
# => 1 event between 05:00 and 05:30
# => 2 events between 09:30 and 10:00

问题:它在列表中循环 48 次

L
,这可能很长。

如何通过

L
上的单个循环执行相同操作?(没有 pandas、numpy 等,但只有 Python 内置模块)?

python performance loops datetime intervals
1个回答
0
投票

您可以通过计算

L
中每个时间的间隔,然后计算该间隔中的出现次数,通过
L
上的单循环传递来实现此目的。

import datetime

L = ["20231017_021000", "20231017_021100", "20231017_021200", "20231017_052800", "20231017_093100", "20231017_093900"]
d = datetime.datetime.strptime("20231017_000000", "%Y%m%d_%H%M%S")

Y = [0 for _ in range(48)]

for l in L:
    # Get the time difference between the current time and the base time (in minutes)
    diff = (datetime.datetime.strptime(l, "%Y%m%d_%H%M%S") - d).seconds // 60

    # Find the interval (index in the result list)
    idx = diff // 30

    # Increment the count for that interval
    Y[idx] += 1

print(Y)
© www.soinside.com 2019 - 2024. All rights reserved.