How to convert 10:00:00 to 10

Asked

Viewed 46 times

1

I’m making a program that calculates time and multiplies by a value.

However, using the library datetime, i get time in format "10:00:00", and if I multiply by 14.00 it returns me an error, because there is no time 140.

Here’s the problem, Python interprets that I’m multiplying the schedule "10:00:00" by 14, being that I want to multiply only the 10 by 14. That said, as I convert "10:00:00" in 10 or "15:40:00" in 15.40? to get the time I am using the function strptime().

1 answer

3


First you have to understand two different concepts: dates/times and durations. Consider the phrases below:

  • the event will be at 10 am
  • the event lasted 10 hours

In the first case, "10 hours" is a time: a specific time of the day.

In the second case, "10 hours" is a duration: an amount of time (it does not say what time started or ended, it only says how long it lasted).

What can be confusing is that they both use the same words (hours, minutes, seconds), and can even be displayed in the same way (a clock shows "10:00" when it is 10:00, a stopwatch shows "10:00" to indicate that 10 hours have passed). But they are different concepts.

That said, in the module datetime we have classes that represent dates/times (such as datetime, date and time) and one representing durations (timedelta). And you said you used strptime, which in this case serves to work with dates and times, but not with durations. So it will not work.


In your case, I believe that "10:00:00" represents a duration of 10 hours, because it only makes sense to multiply it by a number. If it was a time slot, it wouldn’t make sense, because what should the "10:00 times 14" score be? But if it’s a duration of 10 hours, then it makes sense, because multiplying by 14, we would have a duration of 140 hours.

Unfortunately there is no direct way to do the Parsing of a timedelta (there is no equivalent to strptime), then the way is to do it manually:

from datetime import timedelta

s = "10:00:00"
horas, minutos, segundos = map(int, s.split(':'))
duracao = timedelta(hours=horas, minutes=minutos, seconds=segundos)

# multiplicando por 14
nova_duracao = duracao * 14
# obter o total de horas
print(nova_duracao.total_seconds() / 3600) # 140.0

To get the total hours, just use the value of total_seconds and divided by 3600.

One detail: if the entrance is 15:40:00, that nay is equivalent to 15.4, because 40 minutes equals 0.66666... hours, so a duration of 15 hours and 40 minutes equals 15.66666... hours (which multiplied by 14, will give 219.33333... hours).

Browser other questions tagged

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