How can I add up times told by the user?

Asked

Viewed 120 times

-1

from datetime import datetime

inicio = input(
    'Informe o horario de inicio do experimento (formato Horas:Minutos:Segundos): ')
termino = input(
    'Quanto tempo durara o experimento (formato Horas:Minutos:Segundos): ')

convert_inicio = inicio.strftime("%H:%M:%S")
convert_termino = termino.strftime("%H:%M:%S")
soma_horario = convert_inicio + convert_termino

print(soma_horario)

I am using the code described above, but is giving this error:

Esse é o erro que vem causando.

1 answer

2


First of all, there are two important concepts you should know to understand how to solve your problem: "schedules" and "durations". To better understand, consider the two sentences below:

  • the movie starts at two o'clock in the afternoon
  • the film lasts two hours

In the first case, "two hours" refers to a time: a specific time of the day.

In the second case, "two hours" refers to a duration: a quantity of time. In this case, it does not say when the film begins or ends (nor whether it was actually shown). It only tells the duration (how long it lasts) without any relation to any specific time.

The problem is that we use the same words (hours, minutes, etc.) for both, but they are different concepts. To make matters worse, even the way of writing can be the same: for example, many chronometers show 02:00 to indicate a duration of two hours, equal to a clock.

Although different, these concepts are related. If you add a date and duration, the result is another date (if I know the time something starts and how long it lasts, I can calculate the time it ends).

In Python, a duration is represented by timedelta, while dates and times are represented by datetime.


Also, you are confusing the time with the time representation. input returns a string (a text), and a text is not a string datetime. For example, "10:00" and "10:00" are different texts, but both represent the same time (different strings would represent the same datetime).

So you need to generate these objects (convert the strings to datetime and timedelta) before adding them up.

That is, you need to turn the first string into date, using strptime instead of strftime (notice the "p" instead of the "f" in the name - that’s because parsing is the process of transforming a string into a date, and finformation is the opposite process).

The second string should actually be converted to timedelta, because it represents a duration. Unfortunately, there is no direct way to do the Parsing, then you must do it manually:

from datetime import datetime, timedelta

inicio = input('Informe o horario de inicio do experimento (formato Horas:Minutos:Segundos): ')
data_inicio = datetime.strptime(inicio, "%H:%M:%S") # transforma a string em data

duracao = input('Quanto tempo durara o experimento (formato Horas:Minutos:Segundos): ')
horas, minutos, segundos = map(int, duracao.split(':'))
# transforma a string em timedelta
duracao = timedelta(hours=horas, minutes=minutos, seconds=segundos)

# soma a data à duração
termino = data_inicio + duracao

# formata o resultado
print(termino.strftime('%H:%M:%S'))

Notice I only used strftime at the end, to format the datetime (that is, to turn it into a string in a specific format).


The code does not validate if what was typed is in the correct format (if it is not, it will give error).

If you want, you can make one loop that asks the user to type again if the data is invalid:

from datetime import datetime, timedelta

while True:
    try:
        inicio = input('Informe o horario de inicio do experimento (formato Horas:Minutos:Segundos): ')
        data_inicio = datetime.strptime(inicio, "%H:%M:%S")
        break
    except ValueError:
        print('Não foi digitada uma data válida no formato hh:mm:ss')

while True:
    try:
        duracao = input('Quanto tempo durara o experimento (formato Horas:Minutos:Segundos): ')
        horas, minutos, segundos = map(int, duracao.split(':'))
        duracao = timedelta(hours=horas, minutes=minutos, seconds=segundos)
        break
    except ValueError:
        print('Não foi digitada uma duração no formato hh:mm:ss')

termino = data_inicio + duracao
print(termino.strftime('%H:%M:%S'))

Browser other questions tagged

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