goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Tuesday, February 05, 2008

Python - Convert Secs Into Human Readable Time String (HH:MM:SS)

Convert a number of seconds into a human readable time string HH:MM:SS

7046 seconds is: 1 hour 57 mins 26 secs, or 01:57:26

The Function:

def humanize_time(secs):
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs)

The Output:

print humanize_time(7046)
>> 01:57:26
#    Comments [5] |
Tuesday, February 05, 2008 9:50:15 PM (Eastern Standard Time, UTC-05:00)

What's wrong with %02d to eliminate the if statements?

Wednesday, February 06, 2008 3:55:50 AM (Eastern Standard Time, UTC-05:00)
You could also use de mx package.
http://www.egenix.com/products/python/mxBase/mxDateTime/

import mx.DateTime as MX

def humanize_time(secs):
time = MX.DateTimeDeltaFromSeconds(secs)
return time.strftime('%H:%M:%S')

Greetings Arjen
Wednesday, February 06, 2008 7:13:02 AM (Eastern Standard Time, UTC-05:00)
from datetime import timedelta

def humanize_time(secs):
d = timedelta(seconds=secs)
return str(d)
Robin
Wednesday, February 06, 2008 4:33:04 PM (Eastern Standard Time, UTC-05:00)
@Chuck,
thanks for the tip.. i updated the code in the post.
Wednesday, February 06, 2008 4:33:17 PM (Eastern Standard Time, UTC-05:00)
@Ian:
grow up
Comments are closed.