0

I have a list of datetime objects in python and want to aggregate them by the hour. For example if I have a datetime object for

[03/01/2012 00:12:12,
 03/01/2012 00:55:12,
 03/01/2012 01:12:12,
 ...]

I want to have a list of datetime objects for every hour along with a count of the number of datetime objects I have that fall into that bucket. For my example above I would want output of [03/01/2012 00:00:00, 03/01/2012 01:00:00] in one list and a count of the entries in another list: [2,1].

4

2 回答 2

3

您可以使用字典有效地存储此类数据,其中键是小时,值是日期时间对象的列表。例如(未经测试):

l = [datetime.datetime.now(), datetime.datetime.now()] #...etc.
hour_quantization = {}
for dt in l:
    if dt.hour not in hour_quantization:
        hour_quantization[dt.hour] = [dt]
    else:
        hour_quantization[dt.hour].append(dt)

counts = [len(hour_quantization[hour]) for hour in hour_quantization.keys()]

请参阅日期时间的文档条目

于 2012-12-01T19:53:11.010 回答
1

假设您有一个日期时间对象列表,您可以计算每小时有多少个:

from collections import Counter
hours = [t.hour for t in ts]
Counter(hours)

这会给你:

Counter({0: 2, 1: 1})
于 2012-12-01T19:57:48.823 回答