python - Is there a way to "fill in" a series of datetime stamps? -


i have dictionary consists of hourly datetime stamp (seconds since epoch) key, , integer value each. currently, have incomplete series of hourly datetimes, , i'd fill in gaps.

what mean is, if have entry 5/15/2015 17:00:00 , entry 5/15/2015 19:00:00, nothing 5/15/2015 18:00:00, there way iterate , fill in missing hourly keys value of, say, "0".

i have large amount of raw text data includes dates in format: yyyy-mm-dd hh:mm:ss, round hour (by converting seconds since epoch using datetime.datetime.strptime, , truncating minutes , seconds), , count how many times each hour shows in raw data. dictionary looks {'2015-04-02 04:00:00': 1, '2015-06-06 13:00:00': 4, ...}. there hourly gaps , fill them , efficiently.

my current solution involves finding min of dictionary keys, , creating brand new dictionary , filling in every hour until max of original dictionary. redo code wrote create original dictionary, changes values have data change, leaves "empty" values 0. not elegant...

an solution be:

import datetime  # dictionnary data = {...}  start = datetime.datetime.fromtimestamp(0) step = datetime.timedelta(seconds=3600)  stop = datetime.datetime.now() while start <= stop:     key = start.strftime('%d/%m/%y %h:%m:%s')     if key not in data:         data[key] = 0     start+= step 

but, worth filling gaps? or use-case collections.defaultdict?

example:

>>> data = collections.defaultdict(int) >>> print data['5/15/2015 17:00:00'] 0 

Comments