Open In App

Python program to convert seconds into hours, minutes and seconds

Last Updated : 17 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output:

3:25:45

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))


Output:

3:25:45

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))


Output:

3:25:45

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))


Output:

03:25:45

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))


Output

03:25:45

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}')


Output

3:25:45

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads