2

I've values in float and I am trying to convert them into Hours:Min:Seconds but I've failed. I've followed the following post:

Converting a float to hh:mm format

For example I've got a value in float format:

time=0.6 

result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))

and it gives me the output:

00:36 

But actually it should be like "00:00:36". How do I get this?

ZF007
  • 3,708
  • 8
  • 29
  • 48
user3162878
  • 598
  • 3
  • 10
  • 25
  • Show an actual input with an expected output. Right now, the other question is completely irrelevant to what you want (although it is a good starting point). It is very unclear how you intend to format a float as HH:MM:SS. – Mad Physicist Aug 14 '18 at 17:09
  • There are many ways to convert, but they really depend on the *meaning* of the float value. The usual standard is that the value is the fraction of a day that the time is. But your example implies that the value is the fraction of a minute. Which is it, or is the meaning something else? – Rory Daulton Aug 14 '18 at 17:11
  • i ve given example as well – user3162878 Aug 14 '18 at 17:12
  • its the fraction of time. Like 0.6 means 36 seconds – user3162878 Aug 14 '18 at 17:13
  • You can check out my one-liner answer [here](https://stackoverflow.com/a/57018596/8928024) that gives you the 00:00:36 format without performing the regular expression string formatting yourself. – ZF007 Jul 13 '19 at 11:19

3 Answers3

9

You can make use of the datetime module:

import datetime
time = 0.6
result = str(datetime.timedelta(minutes=time))
weakit
  • 216
  • 3
  • 7
1

You're not obtaining the hours from anywhere so you'll first need to extract the hours, i.e.:

float_time = 0.6  # in minutes
hours, seconds = divmod(float_time * 60, 3600)  # split to hours and seconds
minutes, seconds = divmod(seconds, 60)  # split the seconds to minutes and seconds

Then you can deal with formatting, i.e.:

result = "{:02.0f}:{:02.0f}:{:02.0f}".format(hours, minutes, seconds)
# 00:00:36
zwer
  • 24,943
  • 3
  • 48
  • 66
0

Divmod function accepts only two parameter hence you get either of the two Divmod()

So you can try doing this:

time = 0.6
mon, sec = divmod(time, 60)
hr, mon = divmod(mon, 60)
print "%d:%02d:%02d" % (hr, mon, sec)
ANISH TIWARI
  • 111
  • 1
  • 10