Loop Problem and Time Calculation

Asked

Viewed 150 times

1

I want to do a program, where he reads an activity, and the time spent on it.

Example: Lavando o Portão, 10:30 as 12:00, tempo gasto 01:30

I am currently with 3 problems:

  • The way my code is currently I can’t get it to function due to time calculation.

  • I put that would be done 5 activities in case I wanted to leave without a preset limit.

  • I would also like to put a keyword for him to tell me the print, as for example if I type "order", it gives the print with all the collected information.

from datetime import datetime
atividade = [] #Lista de Serviços
hora_inicial = [] #Lista Hora Inicial
hora_final = [] #Lista Hora Final
contagem = 0
while contagem != 5:
    try:
        atividade_p = input(f'Digite o Nome do {contagem + 1}º Atividade: ')
        contagem += 1
        hora_inicia_p = input('Digite a hora Inicial: ')
        hora_final_p = input('Digite a hora Final: ')
        atividade.append(atividade_p)
        hora_inicial.append(hora_inicia_p)
        hora_final.append(hora_final_p)
        d = '$H:$M'
    except ValueError:
        print('Digite um valor valido. Exemplo 10:30')

atividade_1 = atividade [0]
hora_inicia_1 = hora_inicial [0]
hora_final_1 = hora_final [0]
valor_1 = (datetime.strftime(hora_final_1, d) - datetime.strftime(hora_inicia_1, d)

atividade_2 = atividade [1]
hora_inicia_2 = hora_inicial [1]
hora_final_2 = hora_final [1]
valor_2 = (datetime.strftime(hora_final_2, d) - datetime.strftime(hora_inicia_2, d)

atividade_3 = atividade [2]
hora_inicia_3 = hora_inicial [2]
hora_final_3 = hora_final [2]
valor_3 = (datetime.strftime(hora_final_3, d)- datetime.strftime(hora_inicia_3, d)

atividade_4 = atividade [3]
hora_inicia_4 = hora_inicial [3]
hora_final_4 = hora_final [3]
valor_4 = (datetime.strftime(hora_final_4, d) - datetime.strftime(hora_inicia_4, d)

atividade_5 = atividade [4]
hora_inicia_5 = hora_inicial [4]
hora_final_5 = hora_final [4]
valor_5 = (datetime.strftime(hora_final_5, d) - datetime.strftime(hora_inicia_5, d)

print(f'{atividade_1},{hora_inicia_1} ás {hora_final_1}, Tempo gasto {valor_1}')
print(f'{atividade_2},{hora_inicia_2} ás {hora_final_2}, Tempo gasto {valor_2}')
print(f'{atividade_3},{hora_inicia_3} ás {hora_final_3}, Tempo gasto {valor_3}')
print(f'{atividade_4},{hora_inicia_4} ás {hora_final_4}, Tempo gasto {valor_4}')
print(f'{atividade_5},{hora_inicia_5} ás {hora_final_5}, Tempo gasto {valor_5}')

1 answer

3

The problem is you’re using strftime, that converts a date/time into a string. But you want to do the opposite: given a string containing a time, convert it to a datetime. So in this case you should use strptime (note "p" instead of "f" in the method name).

In addition, the format used should be %H:%M, and not $H:$M, as set out in documentation:

t = datetime.strptime('12:00', '%H:%M') - datetime.strptime('10:30', '%H:%M')
print(t) # 1:30:00

In addition, you can improve the code by using a single loop to print out all the activities. Another detail is that in reading the dates you are not validating them (I created a function for this below). And since this function validates the dates, I can return them and save them directly on the respective lists.

The detail is that, to print the objects datetime, I have to use strftime to print only the date and time (because by default the datetime is printed with all fields). Finally, the difference between the dates generates an object timedelta, which when printed uses the "hours:minutes:seconds" format. To print only the hours and minutes, you can remove the last 3 characters (as you are only using hours and minutes to calculate the difference, the seconds will always be zero):

atividade = []  # Lista de Serviços
hora_inicial = []  # Lista Hora Inicial
hora_final = []  # Lista Hora Final
contagem = 0
formato = '%H:%M'

def obter_horario(msg):
    while True:
        try:
            return datetime.strptime(input(msg), formato)
        except ValueError:
            print('Digite um valor valido. Exemplo 10:30')

i = 1
while True:
    atividade_p = input(f'Digite o Nome da {i}º Atividade: ')
    atividade.append(atividade_p)
    hora_inicial.append(obter_horario('Digite a hora Inicial: '))
    hora_final.append(obter_horario('Digite a hora final: '))
    i += 1
    # se digitar "fim", sai do while, senão continua lendo as atividades
    if (input('Digite "fim" para calcular a duração das atividades (ou enter para adicionar outra atividade): ') == 'fim'):
        break


for ativ, inicio, fim in zip(atividade, hora_inicial, hora_final):
    duracao = fim - inicio
    print(f'{ativ},{inicio.strftime(formato)} às {fim.strftime(formato)}, Tempo gasto {str(duracao)[:-3]}')
  • Even better, however, now is appearing the date : Lava the gate,1900-01-01 10:30:00 to 1900-01-12:00, time spent 1:30:00

  • Would you have somewhere where I can be learning more? I have reduced internet, and the pdf I found, only have the basics.

  • @I got the code. As for the study material, I usually use the official documentation of the internet: https://docs.python.org/3/ - there is a link for you to download the pdfs: https://docs.python.org/3/download.html

Browser other questions tagged

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