Home > Mobile >  Convert between hh:mm:ss time and a float that is a fraction of 24 hours
Convert between hh:mm:ss time and a float that is a fraction of 24 hours

Time:11-28

I get as input times (hh:mm:ss) as float - e.g. 18:52:18 is a float 0.786331018518518.

I achieved to calculate the time from a float value with this code:

val = 0.786331018518518
hour = int(val*24)
minute = int((val*24-hour)*60)
seconds = int(((val*24-hour)*60-minute)*60)
print(f"{hour}:{minute}:{seconds}")

How is it possible to calculate the float value from a time - so from 18:52:18 to 0.786331018518518?

And generally isn't there an easier way to convert in both directions between float and time (I was thinking about the datetime module but was not able to find anything for this)?

CodePudding user response:

What you have is an amount of time, in day unit

You can use datetime.timedelta that represents a duration

val = 0.786331018518518
d = timedelta(days=val)
print(d)  # 18:52:19

val = d.total_seconds() / 86400
print(val)  # 0.7863310185185185

From your hour/minute/seconds variables it would be

print(hour / 24   minute / 1440   seconds / 86400)

CodePudding user response:

I'm assuming the float-value is the time in days.

To get the float-value from time, you can convert each of them (hours, minutes, seconds) to days and add them all up.

So hours/24 minutes/60/24 seconds/60/60/24 would work.

  • Related