How do I convert seconds to hours, minutes and seconds?
To swiftly convert seconds to hours, minutes, and seconds in Python, lean on the built-in divmod()
function as follows:
This results in an output of 1h 1m 1s.
Showcasing the timedelta feature in Python
Leveraging timedelta for simple conversions
Python's datetime.timedelta
can convert a large number of seconds into a more human-friendly format of hours, minutes, and seconds.
Using time.gmtime for handling more than 24 hours
For cases where the seconds translate to more than a day, you can utilize time.gmtime
. However, its usage is a double-edged sword—it doesn’t wrap around after 24 hours! Hence, use with caution.
String formation: Making it readable!
Formatting timespan with f-strings
For more precise output rendering, f-strings work excellently. When you want your timespan formatted neatly, don't forget the power of f-strings.
The humanfriendly library: A formatting friend
Consider humanfriendly
if your output will be consumed by non-programmers or where readability is a premium.
How fast do we go? Benchmarking time conversion
Evaluating performance with timeit
Performance matters in coding. Analyze the speed of different solutions with Python's built-in timeit
module:
Advanced handling and edge case scenarios
Handling overflow and negative input
Ensure your solution handles negative inputs for an all-encompassing solution.
Working with large numbers
Python easily handles large numbers, so rest easy when capturing significant timespans.
Was this article helpful?