I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?
+4
A:
def GetInHMS(seconds):
hours = seconds / 3600
seconds -= 3600*hours
minutes = seconds / 60
seconds -= 60*minutes
return "%02d:%02d:%02d" % (hours, minutes, seconds)
Response from comments:
If you want to remove the hours part if there are no hours, you can just add in an extra if statement:
def GetInHMS(seconds):
hours = seconds / 3600
seconds -= 3600*hours
minutes = seconds / 60
seconds -= 60*minutes
if hours == 0:
return "%02d:%02d" % (minutes, seconds)
return "%02d:%02d:%02d" % (hours, minutes, seconds)
>>> GetInHMS(3964)
'01:06:04'
>>> GetInHMS(1234)
'20:34'
>>> GetInHMS(12345)
'03:25:45'
Smashery
2009-04-21 23:14:09
Is there any way to not show hours if there is a 0 there easily?
Specto
2009-04-21 23:17:03
Just return a shortened string if h == 0
FogleBird
2009-04-21 23:18:16
I've put a response in my answer, above.
Smashery
2009-04-21 23:22:57
Hrm, I keep getting an error, posted below.
Specto
2009-04-21 23:32:08
+17
A:
By using the divmod()
function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print "%d:%02d:%02d" % (h, m, s)
Brandon Craig Rhodes
2009-04-21 23:15:54
I second Paolo's statement - haven't heard of divmod before. I'll have to remember it.
Smashery
2009-04-21 23:50:11
I edited your answer to include a link to the documentation, as it is encouraged to do whenever possible.
Paolo Bergantino
2009-04-22 09:00:56
+25
A:
or you can do
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
SilentGhost
2009-04-21 23:22:15
This is the best way, IMHO, as you can then use arithmetic on the timedelta and any datetime objects.
Matthew Schinckel
2009-04-22 03:13:38