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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With