Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a float to hh:mm format

I want to print a float value that I've got after performing some math as time string in the hh:mm format. Currently I have the float like 9.888888888888886 and I want it in time like 09:50. I have tried the following code:

    time = str(time)
    time = time.split(".")
    time[1] = float(time[1])
    time[1] *= 0.6
    time[1] = str(time[1])

and when I print I use

    str(time[0]) + ":" + time[1][:2]

Any way to achieve this effect consistently? With more advanced inputs my above code does not work properly, and outputs the wrong time.

like image 649
Liam Rahav Avatar asked Dec 16 '14 03:12

Liam Rahav


People also ask

How do you convert float to time?

There are a number of ways to convert float to time. However, we use the Math. floor() and Math. round() function from the Javascript Math object.

How do you shorten a float?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.


1 Answers

For python 3.7 version this becomes an one-liner.

x = 9.888888888888886

print (str(datetime.timedelta(hours=x))[:-3])

(Here the time-string minus the last three chars is printed.)

Result 1 : 9:53

Alternatively if you needs seconds:

print (datetime.timedelta(hours=x))

Result 2 : 9:53:20

And finally if you go beyond the 24hour mark timedelta shows the added day as well:

x = 39.888888888888886

Result 3 : 1 day, 15:53:20

like image 175
ZF007 Avatar answered Oct 17 '22 12:10

ZF007