iterate through timeslices

Posted on 2009-04-20
Last Modified: 2013-11-05
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?

Question by:paulkramer
    LVL 39

    Accepted Solution

    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
                raise StopIteration
    if __name__=='__main__':
        ts = timeslice(0,30,60 * 10) # 10 hours
        for t in ts:
            print t

    Open in new window


    Author Comment

    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?
    LVL 28

    Assisted Solution

    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

    Open in new window

    LVL 28

    Expert Comment

    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.)
    LVL 39

    Expert Comment

    by:Roger Baklund
    paulkramer, I believe pepr answered all your additional questions, is there anything else that is unclear?

    Author Comment

    No, thank you both very much for your help.
    LVL 28

    Expert Comment

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

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


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
    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…
    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 …

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now