【问题标题】:Use python to count the number of events in a specified amount of time使用python统计指定时间内的事件数
【发布时间】:2015-01-14 21:34:35
【问题描述】:

我正在监视特定事件的 json 流。我想计算在特定时间内发生的事件数,比如每分钟的事件数,然后与高水位线进行比较以采取行动。

for l in s.makefile() :
m = json.loads(l)
if 'Event' in m and m['Event'] == 'StarLost' :
    print 'Star Lost at time= ' + str(datetime.datetime.fromtimestamp(m['Timestamp']))

【问题讨论】:

  • 您的问题是什么?你能举一个输入数据和预期输出数据的(小)例子吗?
  • 我正在寻找在迭代 json 流时计算某事发生的次数。计算在 X 时间内发现的 N 个事件。然后可以将该速率与高水阈值进行比较。假设我在 60 秒内收到 4 个事件。如何将“年龄”附加到事件中,使其在 60 秒的时间窗口后“消失”?我认为这是一个统计泊松分布,但不知道如何在 python 中使用或编码。

标签: python events monitoring


【解决方案1】:

保留double-ended queue 并根据您从 json 流中获得的时间戳值插入和弹出项目。

import datetime
from collections import deque

threshold = 4
queue = deque()
for l in s.makefile() :
    # fill the queue
    record = json.loads(l)
    try:
        if record['Event'] == 'StarLost':
            timestamp = datetime.datetime.fromtimestamp(record['Timestamp'])
            print('Star Lost at time {}.'.format(timestamp.isoformat()))
            queue.append((timestamp, record))
    except KeyError:
        pass # there was no 'Event' in the record
    # clear the queue from old records
    try:
        while queue[0][0] < datetime.datetime.now() - datetime.timedelta(seconds=60):
            queue.popleft()
    except IndexError:
        pass # there are no records in the queue.
    # analyze the queue
    if len(queue) > threshold:
        print('There were more than {} events over the last minute!'.format(threshold))

此解决方案假设您有 s.makefile() 不间断地生成 json 数据。 理想情况下,您应该将清除队列的部分和分析队列的部分与填充队列的线程放在不同的线程中,但是如果您自己无法提出上述解决方案,那么threading 不是现在为您服务,尽管我通过使用线程安全的deque 开始了它。如果你想让这个解决方案更好,请阅读它。

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多