Python program to convert seconds into hours, minutes and seconds
Last Updated :
26 Jun, 2025
Given an integer n (in seconds), convert it into hours, minutes and seconds.
Examples:
Input : 12345
Output : 3:25:45
Input : 3600
Output : 1:00:00
Let's look at different ways of doing it in Python.
1. Naive Approach
This approach uses simple mathematical calculations to get the hours, minutes, and seconds.
Python
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
# Driver program
n = 12345
print(convert(n))
Explanation:
- seconds % (24 * 3600) ensures that seconds fit within a 24-hour range.
- seconds // 3600 calculates how many hours are in the given seconds.
- seconds % 3600 calculates the remaining seconds after extracting hours.
- seconds // 60 calculates how many minutes are in the remaining seconds.
- seconds % 60 gives the remaining seconds after extracting minutes.
2. Using divmod()
Using the divmod() function allows for a more efficient solution by performing the division and modulus operations in one step.
Python
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return '%d:%02d:%02d' % (hour, min, sec)
# Driver program
n = 12345
print(convert(n))
Explanation:
- divmod(seconds, 60) returns a tuple containing minutes and remaining seconds.
- divmod(min, 60) returns a tuple containing hours and remaining minutes.
- The result is formatted as 'hours:minutes:seconds' using string formatting
3. Using timedelta (from datetime module)
The datetime module provides a timedelta object which can represent durations, making it easy to convert seconds into a human-readable format.
Python
import datetime
def convert(n):
return str(datetime.timedelta(seconds = n))
# Driver program
n = 12345
print(convert(n))
Explanation: timedelta(seconds=n) function automatically converts the given seconds into the format hours:minutes:seconds.
4. Using time.strftime()
The time.strftime() function gives more control over formatting, and time.gmtime() is used to convert seconds into a special tuple format that strftime() accepts.
Python
import time
def convert(seconds):
return time.strftime("%H:%M:%S", time.gmtime(seconds))
# Driver program
n = 12345
print(convert(n))
Explanation:
- time.gmtime(seconds) converts the seconds into a tuple representing the time in GMT.
- time.strftime("%H:%M:%S", time.gmtime(seconds)) formats the tuple into hours:minutes:seconds.
5. Using dateutil.relativedelta()
The dateutil library provides a convenient way to convert seconds into hours, minutes, and seconds using the relativedelta function.
We need to first install the dateutil library using command:
pip install python-dateutil
The dateutil library provides a convenient way to convert seconds into hours, minutes, and seconds using the relativedelta function. Here is an example of how this can be done:
Python
from dateutil import relativedelta
def convert(n):
rd = relativedelta.relativedelta(seconds=n)
return "{}:{:02d}:{:02d}".format(rd.hours, rd.minutes, rd.seconds)
# Driver program
n = 12345
print(convert(n))
#This code is contributed by Edula Vinay Kumar Reddy
Explanation:
- relativedelta(seconds=n) calculates the duration of n seconds and returns it as a relativedelta object.
- The hours, minutes, and seconds attributes are then extracted and formatted as hours:minutes:seconds.
6. Using a Dictionary for Calculations
This approach uses a dictionary to store the number of seconds in each unit of time (hours, minutes, seconds). It iterates over the dictionary, calculating the number of each unit and formatting the result.
Python
def convert_seconds(seconds):
units = {"hours": 3600, "minutes": 60, "seconds": 1}
values = []
for unit, value in units.items():
count = seconds // value
seconds -= count * value
values.append(count)
return f"{values[0]:02d}:{values[1]:02d}:{values[2]:02d}"
# Driver program
seconds = 12345
print(convert_seconds(seconds))
Explanation:
- "units" dictionary maps time units to their equivalent values in seconds.
- code iterates over this dictionary to calculate hours, minutes, and seconds, storing them in the values list.
- The result is formatted into hh:mm:ss format and returned.
Related articles:
Similar Reads
Python program to print current hour, minute, second and microsecond In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python. Methods useddatetime.now().hour(): This method returns the current hour value of the datetime ob
4 min read
Python program to convert time from 12 hour to 24 hour format Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Now, Let's see How to Convert AM/PM to 24 Hour Time using Python.Note: Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on the 12-hour clock and 12:00:00 on the 24-hour clock.
3 min read
Python program to convert time from 12 hour to 24 hour format Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Now, Let's see How to Convert AM/PM to 24 Hour Time using Python.Note: Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on the 12-hour clock and 12:00:00 on the 24-hour clock.
3 min read
Python program to convert time from 12 hour to 24 hour format Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Now, Let's see How to Convert AM/PM to 24 Hour Time using Python.Note: Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on the 12-hour clock and 12:00:00 on the 24-hour clock.
3 min read
Python program to find difference between current time and given time Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format. Examples:Input : h1=7, m1=20, h2=9, m2=45 Outp
2 min read
Convert string to DateTime and vice-versa in Python A common necessity in many programming applications is dealing with dates and times. Python has strong tools and packages that simplify handling date and time conversions. This article will examine how to effectively manipulate and format date and time values in Python by converting Strings to Datet
6 min read