Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert float into Hours Minutes Seconds?

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?

like image 873
user3162878 Avatar asked Oct 14 '25 20:10

user3162878


2 Answers

You can make use of the datetime module:

import datetime
time = 0.6
result = str(datetime.timedelta(minutes=time))
like image 186
weakit Avatar answered Oct 17 '25 11:10

weakit


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
like image 32
zwer Avatar answered Oct 17 '25 09:10

zwer