I have hours in this format,
72.345, 72.629, 71.327, ...
as a result of performing a calculation in Python. It seems that the simplest way to convert these into HH:MM:SS format is using the datetime module like this:
time = str(datetime.timedelta(seconds = 72.345*3600))
However, that returns a values with days, which I don't want:
'3 days, 0:20:42'
This is the best way my brain came up with the final values I want:
str(int(math.floor(time))) + ':' + str(int((time%(math.floor(time)))*60)) + ':' + str(int(((time%(math.floor(time)))*60) % math.floor(((time%(math.floor(time)))*60))*60))
Which is ridiculously long and probably unnecessary. But it does give me the answer I want:
'72:20:41'
Are there better methods?
Viewed20k times 6 3 I have hours in this format, 72.345, 72.629, 71.327, ... as a result of performing a calculation in Python. It seems that the simplest way to convert these into HH:MM:SS format is using the datetime module like this: time = str(datetime.timedelta(seconds = 72.345*3600))
For example, datetime.timedelta (seconds=6010) will return 1 hour 40 minutes 10 seconds. Next, split the string into individual components to get hours, minutes, and seconds Use Python built-in function divmod () function if you don’t want to include days:
You can easily compute hours, minutes and seconds from your decimal time. You should also notice that you can use string formatting which is really easier to use than string concatenation. time = 72.345 hours = int(time) minutes = (time*60) % 60 seconds = (time*3600) % 60 print("%d:%02d.%02d" % (hours, minutes, seconds)) >> 72:20:42 Share
Steps to convert hours, minutes, seconds to seconds: 1 Split the string into individual components and store it in the hours, minutes, and seconds variable. 2 Multiply hours by 3600 3 Multiple minutes by 60 4 Add all the numbers to the seconds variable. More ...
You do not have to use datetime
. You can easily compute hours, minutes and seconds from your decimal time.
You should also notice that you can use string formatting which is really easier to use than string concatenation.
time = 72.345
hours = int(time)
minutes = (time*60) % 60
seconds = (time*3600) % 60
print("%d:%02d.%02d" % (hours, minutes, seconds))
>> 72:20:42
If you want it to be a little easier to look at, you can always put in:
Time = 72.345
Hours = Time
Minutes = 60 * (Hours % 1)
Seconds = 60 * (Minutes % 1)
print("%d:%02d:%02d" % (Hours, Minutes, Seconds))
Putting %d in the string will cut off any decimals for you.
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