Programming from zero

Convert seconds into hours, minutes, and seconds

easyTypes and operators

Problem statement

A duration like a job's runtime often comes as a single number of seconds, which isn't easy to read at a glance. Breaking it into hours, minutes, and seconds uses two operators together: whole-number division to find how many full units fit, and % to find what's left over for the next unit.

flowchart LR A["3661 seconds"] --> B["/ 3600 → 1 hour"] A --> C["% 3600 → 61 seconds left"] C --> D["/ 60 → 1 minute"] C --> E["% 60 → 1 second left"] classDef input fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef hours fill:#D1FAE5,stroke:#059669,color:#065F46 classDef remainder fill:#FEF3C7,stroke:#D97706,color:#92400E classDef minutes fill:#E0E7FF,stroke:#4F46E5,color:#312E81 classDef seconds fill:#FEE2E2,stroke:#DC2626,color:#991B1B class A input class B hours class C remainder class D minutes class E seconds

Common mistake: in Python, using / instead of // for the hours and minutes step.

TEXT
Wrong: hours = total_seconds / 3600

/ gives a decimal, 1.0169..., which doesn't make sense as "1 hour." // throws away the decimal and keeps just the whole number of hours, 1. Java and C++ don't have this trap, dividing two int values already gives you a whole number automatically.

Your task: given totalSeconds = 3661, print it in the form <hours>h <minutes>m <seconds>s, with minutes and seconds padded to two digits.

Expected output:

TEXT
1h 01m 01s

Approach

  1. hours = totalSeconds // 3600 (Python) or totalSeconds / 3600 (Java/C++, since dividing two ints already drops the decimal).
  2. remainder = totalSeconds % 3600, the seconds left after removing full hours.
  3. minutes = remainder // 60 (or / 60), and seconds = remainder % 60.

Minutes and seconds are padded to two digits, 01 not 1, using each language's zero-padding format:

  • Python: f"{minutes:02d}"
  • Java: String.format("%02d", minutes)
  • C++: std::setfill('0') << std::setw(2) << minutes
total_seconds = 3661
hours = total_seconds // 3600
remainder = total_seconds % 3600
minutes = remainder // 60
seconds = remainder % 60
print(f"{hours}h {minutes:02d}m {seconds:02d}s")