Question : iterate through timeslices

I'm wanting to loop iterate though half hour timeslices in a %H:%M:%S format. One way of doing this would be to save each half hour slice to a tuple and use a for loop:

timeslices = ("00:00:00", "00:30:00" etc...)

for i in timeslices:
   #do processing here

Is there a more efficient way to instantiate this loop?

Answer : iterate through timeslices

Sounds like a job for an iterator. Try this:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
class timeslice:
 
    def __init__(self,start,step,max):
        self.start = start
        self.current = start
        self.step = step
        self.max = max
 
    def __iter__(self):    
        return self
        
    def next(self):
        current = "%02d:%02d:00"%(self.current/60,self.current%60)
        if self.current <= self.max:
            self.current += self.step
            return current
        else:
            raise StopIteration
 
if __name__=='__main__':
    ts = timeslice(0,30,60 * 10) # 10 hours
    for t in ts:
        print t
Open in New Window Select All
Random Solutions  
 
programming4us programming4us