Skip to main content
Programming from zero

Format uptime seconds as days, hours, minutes

mediumFunctions

Problem statement

Uptime usually arrives as one big number of seconds, which is hard to read. You have already split seconds into hours, minutes and seconds. Now wrap that idea in a function that returns readable text like 2d 3h 4m, so you can reuse it for any uptime number.

A day is 86400 seconds, an hour is 3600, and a minute is 60. Whole-number division (// in Python, / on whole numbers in Java and C++) finds how many full units fit, and % finds what is left over.

Common mistake: dividing by 3600 without removing the days first.

TEXT
Wrong: hours = seconds // 3600 (gives 51, not 3)

183840 // 3600 counts all the hours, 51 of them, and 48 of those hours are already counted as 2 days. Take the leftover after the days first: (seconds % 86400) // 3600.

Your task: write a function format_uptime(seconds) that gives back the uptime as <days>d <hours>h <minutes>m, ignoring any leftover seconds. Print the result for 183840 and for 3720.

Expected output:

TEXT
2d 3h 4m
0d 1h 2m

Approach

Work out each part, then join them into text and return it:

  1. days is seconds divided by 86400.
  2. hours is what is left after removing days (seconds % 86400), divided by 3600.
  3. minutes is what is left after removing hours (seconds % 3600), divided by 60.

Each language joins the parts into text a little differently:

  • Python: an f-string, f"{days}d {hours}h {minutes}m".
  • Java: + joins numbers and text, days + "d " + hours + "h " + minutes + "m".
  • C++: numbers must be converted first with std::to_string(days), then joined with +.
def format_uptime(seconds):
    days = seconds // 86400
    hours = (seconds % 86400) // 3600
    minutes = (seconds % 3600) // 60
    return f"{days}d {hours}h {minutes}m"

print(format_uptime(183840))
print(format_uptime(3720))