2011-11-22 23 views
1

給定一個字典列表(來自MongoDB的日誌JSON),其中dict的其中一個值是日期時間值,我需要知道它發生的頻率。獲取排序列表中出現的平均次數

比方說:

[ 
    {"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等)。

回答

6

你可以解析字符串轉換爲日期時間,找到最大和最小,減找到一個timedelta,並指定基於該timedelta時間:

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 
+0

優秀,謝謝! –