You can use the module datetime
, with the guys datetime
, timedelta
and time
. The only detail is that you will need to inform a date, that is, year, month and day, however, as we are only interested in the time, any valid date will be possible, because in the end it will be disregarded. In this example, I used the date 01/01/2017.
The logic is as follows: you can create an object of type datetime
as follows
>>> from datetime import datetime, timedelta, time
>>> hrInicial = datetime(2017, 1, 1, 8, 0, 0)
Note that I had to inform the date initially and after, I informed the time, 8, minutes, 0, and seconds, 0. I can check if the time was set correctly by doing:
>>> print(hrInicial.time())
08:00:00
To add a time interval, we use the type timedelta
. For a 30-minute break, we do:
>>> intervalo = timedelta(minutes=30)
We can add this interval to the initial time with the same sum operator:
>>> novaHora = hrInicial + intervalo
>>> print(novaHora.time())
08:30:00
Note that the time has been incremented as expected. Using this logic, we can create a generic function:
def get_interval (inicio, fim, intervalo):
"""
Retorna a lista de horários entre `inicio` e `fim`, inclusive, com um intervalo definido por `intervalo`.
@param inicio iterable Lista de três valores no formato (hora, minutos, segundos)
@param fim iterable Lista de três valores no formato (hora, minutos, segundos)
@param intervalo iterable Lista de três valores no formato (hora, minutos, segundos)
@return generator
"""
inicio = datetime(2017, 1, 1, *inicio)
fim = datetime(2017, 1, 1, *fim)
iHoras, iMinutos, iSegundos = intervalo
intervalo = timedelta(hours=iHoras, minutes=iMinutos, seconds=iSegundos)
while inicio <= fim:
yield inicio.time()
inicio += intervalo
The parameters will be a list of three values: the first defines the hours, the second the minutes and the third the seconds. This way, we can do:
>>> hrInicial = (8, 0, 0)
>>> hrFinal = (12, 0, 0)
>>> intervalo = (0, 30, 0)
>>> for hora in get_interval(hrInicial, hrFinal, intervalo):
... print(hora)
08:00:00
08:30:00
09:00:00
09:30:00
10:00:00
10:30:00
11:00:00
11:30:00
12:00:00
See working on Ideone.
Excellent solution. I didn’t know the "Yield", very good. Thanks for more of this great help.
– Developer
More information on
yield
: https://answall.com/questions/92921/para-que-serve-o-yield– Woss