Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert time seconds to h:m:s format in Python?
In Python, while working on date and time, converting time seconds to h:m:s (Hours: Minutes: Seconds) format can be done using simple arithmetic operations and built-in modules like datetime and time. The following are several ways to convert time seconds to h:m:s format.
- Using arithmetic operations (Naive Method)
- Using the timedelta class of the datetime module
- Using time.strftime() with time.gmtime()
Using Arithmetic Operations (Naive Method)
This is the simplest way to convert seconds into time in H:M:S format. We use basic mathematical operations like division and modulo to break the total number of seconds into hours, minutes, and remaining seconds.
We extract hours by dividing the total seconds by 3600 (since 1 hour = 3600 seconds), then minutes by dividing the remaining seconds by 60 (1 minute = 60 seconds), and the final remaining seconds are taken using the modulo operation.
Example
The following program demonstrates the conversion of time seconds to Hours: Minutes: Seconds format using basic arithmetic operations −
seconds = 5000000
# Handle days if seconds exceed 24 hours
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
print("%d:%02d:%02d" % (hour, minutes, seconds))
The output of the above code is −
20:53:20
Using the timedelta Class of the datetime Module
The timedelta class in Python's datetime module is used to represent the duration or difference between two dates or times. It breaks the time into days, hours, minutes, and seconds. By passing the total number of seconds to timedelta, we can easily convert it into a readable H:M:S format.
Syntax
The syntax of the timedelta() function is as follows −
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
To convert time in seconds to H:M:S format, we only need to provide the seconds parameter.
Example
In the following program, we convert time seconds to H:M:S format by passing the total number of seconds to the timedelta() function −
import datetime
timedelta_obj = datetime.timedelta(seconds=7896354)
print("Time in H:M:S format:", timedelta_obj)
The output of the above code is −
Time in H:M:S format: 91 days, 9:25:54
Extracting Only Hours, Minutes, Seconds
If you want only the H:M:S part without days, you can extract individual components −
import datetime
seconds = 7896354
timedelta_obj = datetime.timedelta(seconds=seconds)
# Extract components
total_seconds = int(timedelta_obj.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
remaining_seconds = total_seconds % 60
print(f"{hours:02d}:{minutes:02d}:{remaining_seconds:02d}")
The output of the above code is −
2193:25:54
Using time.strftime() with time.gmtime()
The gmtime() method from the time module is used here to convert given seconds into a struct_time (elapsed since epoch, in the form of an object), then we use the strftime() method to format this structure into an H:M:S string.
This method works only within a 24-hour cycle. If the total seconds exceed 86400 (24 hours), it wraps around and restarts from 00:00:00.
Example
In this example, we convert the total seconds (123455) into a structured time object using gmtime(). Then, we use strftime("%H:%M:%S") to get a string showing only hours, minutes, and seconds −
import time
seconds = 123455
time_obj = time.gmtime(seconds)
resultant_time = time.strftime("%H:%M:%S", time_obj)
print("Time in H:M:S format:", resultant_time)
The output of the above code is −
Time in H:M:S format: 10:17:35
Comparison of Methods
| Method | Handles Days | Best For | Limitation |
|---|---|---|---|
| Arithmetic Operations | Optional | Simple cases, custom formatting | Manual calculation required |
| timedelta | Yes | Complex time operations | Includes days in output |
| strftime + gmtime | No | Standard formatting | Wraps around after 24 hours |
Conclusion
Use arithmetic operations for simple conversions with custom formatting. Use timedelta when working with complex time operations that may span multiple days. Use strftime() with gmtime() for standard formatting within 24-hour periods.
