【问题标题】:Get the average number of occurrences in a list of dicts获取字典列表中的平均出现次数
【发布时间】:2011-11-22 20:52:12
【问题描述】:

给定一个字典列表(来自 MongoDB 的日志 JSON),其中字典的值之一是日期时间值,我需要知道它发生的频率。

假设:

[
    {"time": "2010-11-11 03:23:59"},
    {"time": "2010-11-12 10:16:15"},
    {"time": "2010-11-12 14:51:13"},
    ...
]

频率需要像:
3 times in a week

1 time in an hour
取决于频率(如果一天不超过一次,只返回x times in a day,如果不超过一周,只使用x times in a week,等等)。

【问题讨论】:

    标签: python date formula frequency


    【解决方案1】:

    您可以将字符串解析为日期时间,找到最大值和最小值,减去以找到时间增量,然后根据该时间增量指定持续时间:

    import datetime as dt
    data=[
        {"time": "2010-11-11 03:23:59"},
        {"time": "2010-11-12 10:16:15"},
        {"time": "2010-11-12 14:51:13"},
        ]
    
    def freq(data):
        dates=[dt.datetime.strptime(dct['time'],'%Y-%m-%d %H:%M:%S') for dct in data]
        date_min=min(dates)
        date_max=max(dates)
        span=date_max-date_min
        l=len(dates)
        if span<dt.timedelta(hours=1):
            duration='an hour'
        elif span<dt.timedelta(hours=24):
            duration='a day'
        elif span<dt.timedelta(days=7):
            duration='a week'
        else:
            duration='all'
        return l,duration
    
    num,duration=freq(data)
    print('{n} times in {d}'.format(n=num,d=duration))
    

    产量

    3 times in a week
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 2019-07-05
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多