每天/每周的日期时间频率列表

0 投票
1 回答
854 浏览
提问于 2025-04-18 06:09

我想要计算一个列表中有多少天/小时。
为了回答这个问题:“在星期六上午10点发生了多少事件?”

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)

1 个回答

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 这样的字符串转换成一个从 0623 的整数。如果你想要字符串形式的结果,比如从 '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

撰写回答