开发者

Get Intervals Between Two Times

开发者 https://www.devze.com 2022-12-12 07:06 出处:网络
A User will specify a time interval of n secs/mins/hours and then two times (start / stop).开发者_Python百科

A User will specify a time interval of n secs/mins/hours and then two times (start / stop).开发者_Python百科

I need to be able to take this interval, and then step through the start and stop times, in order to get a list of these times. Then after this, I will perform a database look up via a table.objects.filter, in order to retrieve the data corresponding to each time.

I'm making some ridiculously long algorithms at the moment and I'm positive there could be an easier way to do this. That is, a more pythonic way. Thoughts?


it fits nicely as a generator, too:

def timeseq(start,stop,interval):
    while start <= stop:
        yield start
        start += interval

used as:

for t in timeseq(start,stop,interval):
    table.objects.filter(t)

or:

data = [table.objects.filter(t) for t in timeseq(start,stop,interval)]


Are you looking for something like this? (pseudo code)

t = start 
while t != stop: 
    t += interval 
    table.objects.filter(t) 


What about ...

result = RelevantModel.objects.filter(relavant_field__in=[
    start + interval * i 
    for i in xrange((start - end).seconds / interval.seconds)
]) 

... ?

I can't imagine this is very different from what you're already doing, but perhaps it's more compact (particularly if you weren't using foo__in=[bar] or a list comprehension). Of course start and end would be datetime.datetime objects and interval would be a datetime.timedelta object.

0

精彩评论

暂无评论...
验证码 换一张
取 消