Format difference between two dates

Asked

Viewed 110 times

2

I calculated the period between two dates in the format d H : M : S, and now I’m trying to format it, but I still can’t, follow an example of what I want to, and my code:

ENTRADA

Dia 5
08 : 12 : 23
Dia 9
06 : 13 : 23

SAÍDA

3 dia(s)
22 hora(s)
1 minuto(s)
0 segundo(s)
from datetime import datetime

Di = str(input())
Hi = str(input())
Df = str(input())
Hf = str(input())

inicio = f'{Di[4:]} {Hi}'
fim = f'{Df[4:]} {Hf}'
f = '%d %H : %M : %S'
dif = (datetime.strptime(fim, f) - datetime.strptime(inicio, f))
dif = datetime.strftime(dif, "%d dia(s)\n"
                             "%H hora(s)\n"
                             "%M minuto (s)\n"
                             "%S segundo(s)")

print(dif)

I tried formatting on line 12 to 15. I would like you, if possible, to preserve the rest of the logic of my code, to modify only what is really necessary to solve the problem.

  • Just one detail, input already returns a string so do str(input()) is unnecessary. Just do input() that is sufficient

  • Okay, thanks for the tip.

1 answer

1


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.

In this case, by subtracting a date from another, the result is a timedelta.
Unfortunately the current API only allows date formatting (cannot be used strftime with a timedelta), and for durations you have to do manually:

# ... ler dados, etc (igual ao seu código)

# diferença entre datas, "dif" será um timedelta
dif = datetime.strptime(fim, f) - datetime.strptime(inicio, f)

# obter o total de segudos
secs = int(dif.total_seconds())

# calcular o equivalente em dias, horas e minutos
dias, secs = divmod(secs, 24 * 3600)
horas, secs = divmod(secs, 3600)
minutos, secs = divmod(secs, 60)

print(f'{dias} dia(s)\n{horas} hora(s)\n{minutos} minuto(s)\n{secs} segundo(s)')

The idea is to use total_seconds to get the total duration in seconds, and then do some calculations to know how many days, hours and minutes has this duration (for this I use divmod, which already returns at the same time the result of the split and the rest of the same).

Browser other questions tagged

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