Olá. Acho que a melhor solução seria utilizar a biblioteca datetime para isso, mas como a ideia do exercício é treinar "if, elif, else" resolvi tomar o caminho mais longo mesmo! PS: Tive que simplificar as docstrings, se não, não caberia no limite de caracteres do post no forum.
import re
def validar_hora_24h(hora_string: str) -> bool:
"""
Valida se uma string representa um horário válido no formato 24 horas (HH:MM:SS).
"""
regex_hora = r"^(([01]\d)|(2[0-3])):[0-5]\d:[0-5]\d$"
if re.fullmatch(regex_hora, hora_string):
return True
return False
def decompor_hora_24h(hora_string: str) -> dict[str, int]:
"""
Recebe uma string de horário (HH:MM:SS), valida-a e, se for válida,
retorna um dicionário com a hora, minuto e segundo como números inteiros.
"""
if not validar_hora_24h(hora_string):
raise ValueError(
f"Horário inválido: '{hora_string}'. "
"Esperado o formato HH:MM:SS com valores válidos (00:00:00 a 23:59:59)."
)
regex_captura = r"(\d{2}):(\d{2}):(\d{2})"
match = re.match(regex_captura, hora_string)
if match:
hora_str, minuto_str, segundo_str = match.groups()
return {
'hora': int(hora_str),
'minuto': int(minuto_str),
'segundo': int(segundo_str)
}
raise RuntimeError("Falha inesperada na extração.")
def horario_para_segundos(horas: int or float, minutos: int or float, segundos: int or float) -> int:
"""
Converte uma duração (horas, minutos, segundos) para o total de segundos.
Lança um ValueError se os valores de hora, minuto ou segundo estiverem
fora dos limites típicos (0-23, 0-59, 0-59, respectivamente).
"""
if not (0 <= horas <= 23):
raise ValueError(f"Horas devem estar entre 0 e 23. Recebido: {horas}")
if not (0 <= minutos <= 59):
raise ValueError(f"Minutos devem estar entre 0 e 59. Recebido: {minutos}")
if not (0 <= segundos <= 59):
raise ValueError(f"Segundos devem estar entre 0 e 59. Recebido: {segundos}")
segundos_da_hora = int(horas * 3600)
segundos_do_minuto = int(minutos * 60)
segundos_literais = int(segundos)
total_segundos = segundos_da_hora + segundos_do_minuto + segundos_literais
return total_segundos
def main() -> None:
HORARIO_MINIMO: str = '08:00:00'
HORARIO_MINIMO_DECOMPOSTO: dict[str, int] = decompor_hora_24h(HORARIO_MINIMO)
HORA_MINIMA: int = HORARIO_MINIMO_DECOMPOSTO['hora']
MINUTO_MINIMO: int = HORARIO_MINIMO_DECOMPOSTO['minuto']
SEGUNDO_MINIMO: int = HORARIO_MINIMO_DECOMPOSTO['segundo']
HORA_MINIMA_SEGUNDOS: int = horario_para_segundos(HORA_MINIMA, MINUTO_MINIMO, SEGUNDO_MINIMO)
HORARIO_MAXIMO: str = '18:00:00'
HORARIO_MAXIMO_DECOMPOSTO: dict[str, int] = decompor_hora_24h(HORARIO_MAXIMO)
HORA_MAXIMA: int = HORARIO_MAXIMO_DECOMPOSTO['hora']
MINUTO_MAXIMO: int = HORARIO_MAXIMO_DECOMPOSTO['minuto']
SEGUNDO_MAXIMO: int = HORARIO_MAXIMO_DECOMPOSTO['segundo']
HORA_MAXIMA_SEGUNDOS: int = horario_para_segundos(HORA_MAXIMA, MINUTO_MAXIMO, SEGUNDO_MAXIMO)
horario_atual: str = ''
horario_atual_decomposto: dict[str, int] = {}
hora_atual: int = 0
minuto_atual: int = 0
segundo_atual: int = 0
hora_atual_segundos: int = 0
if not HORA_MINIMA_SEGUNDOS < HORA_MAXIMA_SEGUNDOS:
raise ValueError(' "HORA_MINIMA_SEGUNDOS" precisa ser, obrigatóriamente, menor que "HORA_MAXIMA_SEGUNDOS".')
while True:
horario_atual = input('\nDigite a hora atual (formato 24 horas HH:MM:SS): ')
if not validar_hora_24h(horario_atual):
print(
f'Horário inválido: {horario_atual}'
'\nEsperado o formato HH:MM:SS com valores válidos (00:00:00 a 23:59:59).'
)
else:
break
try:
horario_atual_decomposto = decompor_hora_24h(horario_atual)
except ValueError as e:
print(e)
exit(1)
except RuntimeError as e:
print(e)
exit(1)
hora_atual = horario_atual_decomposto['hora']
minuto_atual = horario_atual_decomposto['minuto']
segundo_atual = horario_atual_decomposto['segundo']
hora_atual_segundos = horario_para_segundos(hora_atual, minuto_atual, segundo_atual)
if hora_atual_segundos >= HORA_MINIMA_SEGUNDOS and hora_atual_segundos <= HORA_MAXIMA_SEGUNDOS:
print('Acesso permitido.')
else:
print('Acesso negado.')
if __name__ == '__main__':
main()