Editor

Python Program to Convert Seconds to Hours, Minutes and Seconds

Beginner · Dates and times

This program converts a number of seconds into hours, minutes and seconds: 7384 seconds is 2 hours, 3 minutes and 4 seconds. It uses whole number division to count the full hours and minutes, and the remainder for what is left over.

Program

seconds_to_hours_minutes.py
total_seconds = 7384 # or: total_seconds = int(input("Enter the number of seconds: "))
hours = total_seconds // 3600 # 3600 seconds in an hour
remaining = total_seconds % 3600 # seconds left after the full hours
minutes = remaining // 60
seconds = remaining % 60
print(total_seconds, "seconds is")
print(hours, "hours,", minutes, "minutes and", seconds, "seconds")
print(f"As a clock: {hours:02}:{minutes:02}:{seconds:02}")
Output
7384 seconds is
2 hours, 3 minutes and 4 seconds
As a clock: 02:03:04

How it works

  1. An hour has 3600 seconds, so total_seconds // 3600 gives the number of whole hours.
  2. total_seconds % 3600 is what is left over after taking out those hours.
  3. The leftover is split the same way with 60, into whole minutes and the remaining seconds.
  4. :02 in the f-string pads a number to two digits with a leading zero, so 3 is shown as 03 on the clock.

Other ways to write it

Using divmod(), with days too

Using divmod(), with days too
total_seconds = 100000
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
print(f"{total_seconds} seconds = {days} day, {hours} hours, {minutes} minutes and {seconds} seconds")
Output
100000 seconds = 1 day, 3 hours, 46 minutes and 40 seconds

divmod(a, b) returns the quotient and the remainder together, and chaining it carries on from minutes to hours to days.

Using timedelta

Using timedelta
from datetime import timedelta
for s in [45, 7384, 100000]:
print(s, "seconds =", timedelta(seconds=s))
Output
45 seconds = 0:00:45
7384 seconds = 2:03:04
100000 seconds = 1 day, 3:46:40

A timedelta prints itself as hours:minutes:seconds and adds the days once there are more than 24 hours.

Try it yourself

Write the reverse: turn 1 hour, 15 minutes and 30 seconds into seconds, and check that you get 4530.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises