Iteration with variable of type 'TIME'

Asked

Viewed 50 times

0

I am doing a project in which I need to perform a loop that increases minute by minute of a variable from two times informed.

I thought of logic as follows:

 vHoraInicial = '13:30'
 vHoraFinal   = '15:00'

While vHoraInicial <= vHoraFinal:
        print (vHoraInicial)
        vHoraInicial = vHorainicial + 1

Result of the print: 13:30

13:31

13:32

...

15:00

But I don’t know the functions that help me to manipulate variable 'TIME'. Anyone have any idea?

Thank you

  • And how will it work in situations where the day turns ? These cases are supposed to be contemplated ?

  • Actually no Isac, I just want to check the maximum from 00:00 till 23:59

1 answer

1


The way it is, you’re not working with schedules, you’re working with string. For us it turns out to be the same thing, but for the computer they are completely different. To work with schedules, you will need the module datetime.

import datetime

start = datetime.datetime(year=2018, month=5, day=8, hour=13, minute=30)
end = datetime.datetime(year=2018, month=5, day=8, hour=15, minute=0)
interval = datetime.timedelta(minutes=1)

while start <= end:
    print(start)
    start += interval

See working on Repl.it | Ideone | Github GIST

Note that, working with schedules, you need to set the date, since if the schedule exceeds 23:59:59, the day will be changed. If there is the guarantee that it will always be on the same day the start and end time, for practical purposes, you can set the date as constant and, instead of directly displaying the date, format it, print(format(start, '%H:%M:%S')).

  • Anderson excellent, worked here! For the function I will use I have the guarantee that will never exceed the day, so I will keep the date fixed. Thank you very much friend!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.