Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I easily manipulate a timestamp key in a Python dictionary?

I just started using Python as hobby, so forgive me if this is a dumb question.

I recently installed a power meter on my computer, and I'm using it to track its power consumption. It gives me real-time minute readings exported to a csv file.

I have parsed and read the file, and now I have a dictionary where the key is a timestamp, stored as a struct_time from the time library. Currently, the dictionary has readings which were taken every minute. I'd like to create a new dictionary whose keys are hour timestamps, and whose values are the sum of the individual minute readings.

I thought about looping through the dictionary with a counter mod 60, but I'm told that isn't very Pythonic. Also, there's no guarantee that there exists 60 readings for every hour. How should I do this?

like image 456
krapht Avatar asked Feb 03 '26 07:02

krapht


1 Answers

If my understanding to your question is right, this should do the job:

from collections import defaultdict
output = defaultdict(int)
for key, value in readings.iteritems():
    output[key.tm_hour] += value

The advantage of using defaultdict is that it will handle the case of missing hours by returning 0 as a value.

Edit:

As Cristian pointed out the OP might have readings for several days. In that case I follow the suggestion first introduced by Adam Rosenfield with a slight modification:

from collections import defaultdict
from datetime import datetime
output = defaultdict(int)
for key, value in readings.iteritems():
    output[datetime(*x[:4])] += value

This will construct the date from the day, month, year and hour without minutes or seconds.

like image 165
Nadia Alramli Avatar answered Feb 04 '26 19:02

Nadia Alramli