2014-05-10 31 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值的任何密钥。

相关问题