Python program to convert seconds into hours, minutes and seconds
Last Updated :
17 May, 2023
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
Approach #1 : Naive This approach is simply a naive approach to get the hours, minutes and seconds by simple mathematical calculations.
Python3
# Python Program to Convert seconds
# into hours, minutes and seconds
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))
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #2 : Alternate to the Naive approach By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations.
Python3
# Python Program to Convert seconds
# into hours, minutes and seconds
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))
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #3 : Using timedelta (Object of datetime module) Datetime module provides timedelta object which represents a duration, the difference between two dates or times. datetime.timedelta can be used to represent seconds into hours, minutes and seconds format.
Python3
# Python Program to Convert seconds
# into hours, minutes and seconds
import datetime
def convert(n):
return str(datetime.timedelta(seconds = n))
# Driver program
n = 12345
print(convert(n))
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #4 : Using time.strftime() time.strftime() gives more control over formatting. The format and time.gmtime() is passed as argument. gmtime is used to convert seconds to special tuple format that strftime() requires.
Python3
# Python Program to Convert seconds
# into hours, minutes and seconds
import time
def convert(seconds):
return time.strftime("%H:%M:%S", time.gmtime(n))
# Driver program
n = 12345
print(convert(n))
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #5 :
To install the dateutil library, you can use the following command:
pip install python-dateutil
This will install the dateutil library and make it available for use in your Python programs.
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:
Python3
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
This approach uses the relativedelta function from the dateutil library to create a relativedelta object representing the duration of the number of seconds. It then formats the hours, minutes, and seconds attributes of the object and returns the result as a string.
This approach has a time complexity of O(1) and an auxiliary space complexity of O(1). It is a simple and efficient way to convert seconds into hours, minutes, and seconds using the dateutil library.
Approach#6: Using a dictionary to store the 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 adding it to a list. Then it formats the list as a string in the format "hh:mm:ss" and returns it.
Algorithm
1. Create a dictionary that maps the names of the units to their sizes in seconds
2. Iterate over the dictionary, calculating the number of each unit and adding it to a list
3. Format the result as a string in the format "hh:mm:ss"
4. Return the result
Python3
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}"
seconds = 12345
print(convert_seconds(seconds))
Time complexity: O(1), because the number of iterations in the loop is constant, and each iteration takes constant time to execute.
Space complexity: O(1), because the only extra space used is for the dictionary and the list of values, both of which have a constant size.
Approach#7: Using map()+lambda
This approach uses anonymous functions and integer division and modulus operators to convert seconds into hours, minutes, and seconds and then formats the output as a string.
Algorithm
1. Initialize a variable seconds with an integer value representing the number of seconds.
2. Create an anonymous function that converts the number of seconds into hours, minutes, and seconds using integer division and modulus operators.
3. Use the map() function with the anonymous function to apply the conversion to all the elements of a list containing the values to be converted.
4. Unpack the result of map() into variables h, m, and s.
5. Use f-strings to format the output as a string of the form hours:minutes:seconds.
6. Print the formatted string.
Python3
seconds = 12345
h, m, s = map(lambda x: int(x), [seconds/3600, seconds%3600/60, seconds%60])
print(f'{h}:{m:02d}:{s:02d}')
Time Complexity: O(1), because the number of operations performed by the code is constant, regardless of the value of seconds.
Auxiliary Space: O(1), because the code uses only a constant amount of memory to store the variables and the output string.
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
Measure time taken by program to execute in Python
Measuring the execution time of a Python program is useful for performance analysis, benchmarking, and optimization. Python provides several built-in modules to achieve this with ease. In this article, we'll explore different ways to measure how long a Python program takes to run.Using the time Modu
2 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
Python program to convert unix timestamp string to readable date
In this article, we are going to see the conversion of the Unix timestamp string to a readable date. This can be done with the help of fromtimestamp() and strftime() functions in Python. Example:Â Input: 1294113662 Output: 2011-01-04 09:31:02 Explanation: Unix timestamp string to a readable date Wha
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
Convert Epoch Time to Date Time in Python
Epoch time, also known as Unix time or POSIX time, is a way of representing time as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Converting epoch time to a human-readable date and time is a common task in programming, especially i
3 min read
Python - Time Strings to Seconds in Tuple List
Given Minutes Strings, convert to total seconds in tuple list. Input : test_list = [("5:12", "9:45"), ("12:34", ), ("10:40", )] Output : [(312, 585), (754, ), (640, )] Explanation : 5 * 60 + 12 = 312 for 5:12. Input : test_list = [("5:12", "9:45")] Output : [(312, 585)] Explanation : 5 * 60 + 12 = 3
7 min read
Convert "unknown format" strings to datetime objects in Python
In this article, we are going to see how to convert the "Unknown Format" string to the DateTime object in Python. Suppose, there are two strings containing dates in an unknown format and that format we don't know. Here all we know is that both strings contain valid date-time expressions. By using th
3 min read
How To Create a Countdown Timer Using Python?
In this article, we will see how to create a countdown timer using Python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format 'minutes: seconds'. We will use the time module here.Step-by-Step Approac
2 min read