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).
Just one detail,
input
already returns a string so dostr(input())
is unnecessary. Just doinput()
that is sufficient– hkotsubo
Okay, thanks for the tip.
– Afuro Terumi