Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
Solved

# iterate through timeslices

Posted on 2009-04-20
Medium Priority
254 Views
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?

0
Question by:paulkramer
• 3
• 2
• 2

LVL 39

Accepted Solution

Roger Baklund earned 1000 total points
ID: 24190179
Sounds like a job for an iterator. Try this:
``````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
``````
0

Author Comment

ID: 24190286
Sorry, I haven't yet advanced to iterators in the tutorials. I understand the majority of this code apart from the line:

current = "%02d:%02d:00"%(self.current/60,self.current%60)

What does "02" in the string format represent? Also, why is self.current divided by 60?
0

LVL 29

Assisted Solution

pepr earned 1000 total points
ID: 24190412
The self.current is the time in minutes. Divided by 60 you get the time in hours. Modulo by 60 you get the fraction of the next hour. Minor enhancement should be to use the // operator instead of / as the later is going to return real number in new versions of Python.

Alternative solution would be to use the Python generator which looks like a function that uses "yield" instead of "return". Iteration means (generally) going through the all related values -- here through the time slices (think about "next value" and then "next value", and next, next,... until you have not the next value).

Python "for" loop generalizes the use of iterators. It is considered the most natural mean for looping in Python -- and not only in Python; however, Python supports it very cleanly syntactically.

Here the iterator is the object that returns all the values via "next".

See the alternative solution that copies the paulkramer's core via the generator...
``````def timeslices(startTime, step, maxTime):
'''Generates formatted timestamps. Times are in minutes.'''
myTime = startTime
while myTime <= maxTime:
yield '%02d:%02d:00' % (myTime // 60, myTime % 60)
myTime += step

if __name__=='__main__':
for s in timeslices(0, 30, 60 * 10): # 10 hours
print s
``````
0

LVL 29

Expert Comment

ID: 24190427
The %02d is the prescription for formatting: integer on 2 character positions and when the number is shorter, fill the positions by the zeros from the left(i.e. 00, 01, 02, ..., 09, 10, 11, etc.)
0

LVL 39

Expert Comment

ID: 24211118
0

Author Comment

ID: 24211186
No, thank you both very much for your help.
0

LVL 29

Expert Comment

ID: 24212300
To crx: "See the alternative solution that copies the paulkramer's core via the generator..."

Sorry, it was your solution (crx), indeed. ;)

Petr
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
###### Suggested Courses
Course of the Month10 days, 19 hours left to enroll