In this article, we will learn about the solution to the problem statement given below.
Problem statement: We are given time, we need to convert seconds into hours & minutes to seconds.
There are three approaches as discussed below−
Approach 1: The brute-force method
Example
def convert(seconds): seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%02d:%02d:%02d" % (hour, minutes, seconds) #formatting n = 23451 print(convert(n))
Output
06:30:51
Approach 2: The datetime module
Example
#using date-time module import datetime def convert(n): return str(datetime.timedelta(seconds = n)) n = 23451 print(convert(n))
Output
6:30:51
Approach 3: THe time module
Example
#using time module import time def convert(seconds): return time.strftime("%H:%M:%S", time.gmtime(n)) n = 23451 print(convert(n))
Output
06:30:51
Conclusion
In this article, we have learned about how we can convert seconds into hours, minutes and seconds.