Python: convert seconds to hh:mm:ss


Please, how to convert an int (number a seconds) to these formats: mm:ss or hh:mm:ss ?

I need to do this with Python code (and if possible in a Django template ?).

Thank you very much ;-)

9/5/2009 10:33:21 PM

Accepted Answer

I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):

>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))

Doing it in a Django template's more finicky, since the time filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:

>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
...     tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))

Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.

9/6/2009 2:45:32 PM

>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow