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
7384 seconds is 2 hours, 3 minutes and 4 seconds As a clock: 02:03:04
How it works
- An hour has 3600 seconds, so
total_seconds // 3600gives the number of whole hours. total_seconds % 3600is what is left over after taking out those hours.- The leftover is split the same way with 60, into whole minutes and the remaining seconds.
:02in 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises