views:

153

answers:

3

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?

+4  A: 

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

t = start 
while t != stop: 
    t += interval 
    table.objects.filter(t)
Vijay Mathew
That's so simple it's unreal. I really need to learn how to 'step back' from a problem.
day_trader
i would use `t <= stop` because `(stop-start)%interval` may be different from 0
Adrien Plisson
+1  A: 

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.

ozan
+3  A: 

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)]
Useless
I really like your third suggestion! :)
day_trader
Hmmm. When I do a simple: `list = []; data = [list.append(t) for t in timeseq(1258558882,1258558982,10)]` I am returned with `[None, None, None, None, None, None, None, None, None, None, None]` why is this?
day_trader
`list.append(t)` evaluates to `None` (but has a side-effect on list - try printing that).You can just write `data = list(timeseq(1258558882,1258558982,10))` if you want to evaluate the list.
Useless
New correct answer as this is exactly what I want! thanks a lot :)
day_trader
Though, how do you print the 'side-effect on list'? :S Your last part worked perfectly though, but I'm just curious as to what you're referring to! thanks a lot :)
day_trader
The code you posted starts with empty `list = []`.Then it constructs another list with the comprehension `data = [...`.The values for that comprehension are the return values from the calls to `list.append(t)`.Now, `list.append(t)` returns `None`, but modifies `list` - ie, it has a side-effect rather than being a pure function that returns a result.If you print `list` as well as `data`, you should see `list` has the results you wanted, although `data` is the sequence of `None` you posted before.Did I explain that clearly? Hope this helps your comprehension ;D
Useless