NIH
NIH

Reputation: 161

aggregating datetime objects in python to the hour

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].

Upvotes: 0

Views: 789

Answers (2)

eqzx
eqzx

Reputation: 5579

You could store that kind of data efficiently with a dictionary where the keys are hours and the values are lists of the datetime objects. e.g. (untested):

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()]

see the doc entry on datetime

Upvotes: 3

Burhan Khalid
Burhan Khalid

Reputation: 174662

Assuming you have a list of datetime objects, you can count how many of each hour there are:

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

This will give you:

Counter({0: 2, 1: 1})

Upvotes: 1

Related Questions