This question already has an answer here:
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 ;-)
This question already has an answer here:
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 ;-)
You can calculate the number of minutes and hours from the number of seconds by simple division:
Here
//
is pythons integer division.Not being a python person but easiest without any libraries just:
Updated code, thanks sth
Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:
Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59
Code that does what was requested, with examples, and showing how cases he didn't specify are handled:
You can--and probably should--store this as a timedelta rather than an int, but that's a separate issue and timedelta doesn't actually make this particular task any easier.
If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:
Now conversion of seconds to format string is a fast dict lookup:
prints
Have you read up on the datetime module?
Edit/update: SilentGhost's answer has the details my answer leaves out. If you like this answer, +1 his as well (or instead). Reposted here: