I have time series data that I now store in a dictionary where dictionary keys are datetime.datetimeobjects. Sort of:
data[datetime.datetime(2012,5,14,15,28,2)]={'error':error,'flags':flags,'value':value}
I have a question: What is the best way to find the next two times (before and after) a certain time? I need this function as quickly as possible, because it is called (~ 10000) inside a loop linearly interpolating between the two nearest points.
Currently, I have one working method that takes a ridiculously long time, because it looks through all the keys (~ 50,000):
def findTime(time):
keys=data.keys()
bdt=10000000000000000000
adt=10000000000000000000
minKey=False
maxKey=False
for key in keys:
dt=(time-key).total_seconds()
if abs(dt)<bdt and dt>0:
bdt=abs(dt)
minKey=key
elif abs(dt)<adt and dt<0:
adt=abs(dt)
maxKey=key
return minKey,maxKey
My attempt to use bisect:
def findTime(time):
keys=data.keys()
l,r = bisect.bisect_left(time,keys), bisect.bisect_right(time,keys)
return l,r
Unfortunately, this causes an error:
TypeError: 'datetime.datetime' object does not support indexing
Any help would be appreciated.