Federer
Federer

Reputation: 34805

Get Intervals Between Two Times

A User will specify a time interval of n secs/mins/hours and then two times (start / stop).

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?

Upvotes: 0

Views: 503

Answers (3)

Useless
Useless

Reputation: 67802

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

Upvotes: 4

ozan
ozan

Reputation: 9331

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.

Upvotes: 1

Vijay Mathew
Vijay Mathew

Reputation: 27204

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

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

Upvotes: 4

Related Questions