2014-05-10 35 views
0

我想要計算列表中的天數/小時數。 要回答這個問題:「週六10AM發生了多少事件?」日期時間列表中每週日/小時的頻率

from itertools import groupby, izip 

import time 
from datetime import date 

# Calculate number of events that happened 
d= ["2009-04-28 11:00:00 AM","2009-04-28 12:00:00 PM","2009-05-28 01:00:00 PM","2009-05-27 02:00:00 PM","2009-05-27 03:00:00 PM" ] 


dt = [time.strptime(l, '%Y-%m-%d %I:%M:%S %p') for l in d] 
cr_dates_i=[int('{0}{1:02d}'.format(c.tm_wday, c.tm_hour)) for c in dt] 
counts = [(k, len(list(g))) for (k, g) in groupby(cr_dates_i)] 
print counts 


eg: 
2014-05-10 12:00:00 PM ==> Friday+12 ==> 512 (Sunday 0 - Saturday 6) 

問題是:我現在如何影響到每個日期,頻率的數量?所有可能的事件甚至爲零。

週日(0) - >週六(6)

00:00 - > 23:00

至於結果,我應該有(000,623 ..)

回答

0

所以首先像你表達我會定義一個函數來轉換日期時間爲數字:

import time 

def datetime_to_num(timestr): 
    # convert string to time object 
    dt = time.strptime(timestr, "%Y-%m-%d %I:%M:%S %p") 
    numday = (dt.tm_wday + 1) % 7 # get new day number 
    numhour = dt.tm_hour # get hour number 
    return int("{}{}".format(numday, numhour)) # return correct int 

這會採取的形式2014-05-10 12:00:00 PM的字符串,並將其轉換爲從0整數正如你所描述的那樣。如果你想要字符串,所以你可以從'000''623',你可以刪除return語句中的int(),並且所有東西都應該基本相同。那麼你只需要以某種方式來計算這些數字的頻率。所以通常一個簡單的方法是使用defaultdict

from collections import defaultdict 

dtdict = defaultdict(int) # default count = 0 

for dtstr in strlist: # for each string to process 
    dtdict[datetime_to_num(dtstr)] += 1 # count it 

你會然後結束與形式的頻率的一個字典:

# for example: 
{ '0' : 1, 
    '1' : 3, 
    '523' : 7, 
    '623' : 4, 
} 

隨着被訪問時不存在具有0值的任何密鑰。

相關問題