37. Format a duration
Write a function format_duration(seconds) that takes a whole number of seconds and returns it as text in the form
h:mm:ss:
his the number of whole hours, written as it is:0,7or25. It isn't padded, and it doesn't wrap round after 24, since this is a length of time, not a time of day.mmis the minutes left over, 0 to 59, always written with two digits:05, not5.ssis the seconds left over, 0 to 59, also two digits.
So 3725 seconds, which is 1 hour, 2 minutes and 5 seconds, becomes "1:02:05", and 0 seconds is "0:00:00".
Example 1
Input
seconds = 3725Output
"1:02:05"Explanation3725 = 3600 + 2 * 60 + 5.
Example 2
Input
seconds = 59Output
"0:00:59"ExplanationUnder a minute: hours and minutes are 0.
Example 3
Input
seconds = 90000Output
"25:00:00"ExplanationExactly 25 hours: the hours go past 24.
Constraints
secondsis a whole number from 0 to 1,000,000.
Submit also runs 8 more tests you can't see.
Practises Variables and Types (lesson 2).
- There are 3600 seconds in an hour:
seconds // 3600is the whole hours, andseconds % 3600is what is left over. - Split what is left the same way with 60:
// 60gives the minutes and% 60the seconds. - An f-string can pad a number:
f"{5:02d}"is"05"(at least 2 digits, with 0 in front). Use it for the minutes and seconds, but not the hours.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def format_duration(seconds):
"""Write a number of seconds as hours, minutes, seconds.
seconds: int, 0 or more
Returns: str, "h:mm:ss" with minutes and seconds always
two digits
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.