Format uptime seconds as days, hours, minutes
Problem statement
System uptime is often reported in seconds. Write a function format_uptime(seconds) that returns a string like 2d 3h 15m, ignoring leftover seconds. Print the result for 184500 seconds.
Examples
Example 1
Input: format_uptime(184500)
Output: 2d 3h 15m
Explanation: 184500 seconds is 2 days (172800) plus 3 hours (10800) plus 15 minutes (900).
Hints
Approach
Optimal
Break the total down from the largest unit to the smallest. divmod(seconds, 86400) returns two numbers: how many whole days fit, and how many seconds are left over. Repeat with the leftover and 3600 to get hours, then with 60 to get minutes. divmod(a, b) is the same as computing a // b (whole-number division) and a % b (the remainder) separately. The function returns the formatted string, and the caller prints it.
def format_uptime(seconds): days, rest = divmod(seconds, 86400) hours, rest = divmod(rest, 3600) minutes, _ = divmod(rest, 60) return f"{days}d {hours}h {minutes}m" print(format_uptime(184500))Follow-up questions
- Leave out the days part when it is 0, so 3900 seconds gives
1h 5m.
Frequently asked questions
By convention, _ is a name for a value you have to receive but do not plan to use, here the leftover seconds. Python treats it as a normal variable.
On Linux, the first number in /proc/uptime is the uptime in seconds. Many APIs and monitoring tools also report durations in seconds.