tags:

views:

3512

answers:

3

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
Is there any way to not show hours if there is a 0 there easily?
Specto
Just return a shortened string if h == 0
FogleBird
I've put a response in my answer, above.
Smashery
Hrm, I keep getting an error, posted below.
Specto
+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
+1 for divmod. It's _made_ for situations like this.
John Fouhy
I second Paolo's statement - haven't heard of divmod before. I'll have to remember it.
Smashery
I edited your answer to include a link to the documentation, as it is encouraged to do whenever possible.
Paolo Bergantino
+25  A: 

or you can do

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
SilentGhost
Very nice - I'll have to keep that one in my toolbox
Smashery
This is the best way, IMHO, as you can then use arithmetic on the timedelta and any datetime objects.
Matthew Schinckel