pythontime

Convert seconds to hh:mm:ss in Python


How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss?

I need to do this with Python code.


Solution

  • 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))
    '03:25:45'
    

    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)}))
    u'03:25:45'
    

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