Explain Codes LogoExplain Codes Logo

How do I convert seconds to hours, minutes and seconds?

python
timedelta
datetime
performance
Nikita BarsukovbyNikita Barsukov·Sep 6, 2024
TLDR

To swiftly convert seconds to hours, minutes, and seconds in Python, lean on the built-in divmod() function as follows:

seconds = 3661 h, r = divmod(seconds, 3600) # 3600 seconds = 1 hour m, s = divmod(r, 60) # 60 seconds = 1 minute print(f"{h}h {m}m {s}s")

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.

from datetime import timedelta seconds = 3661 td = timedelta(seconds=seconds) print(str(td)) # Outputs: '1:01:01'

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.

import time seconds = 90061 # A span of more than one day formatted_time = time.strftime('%H:%M:%S', time.gmtime(seconds)) print(formatted_time) # Outputs: '01:01:01', not '25:01:01'

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.

# Let's add a zero before single-digit hours, minutes, seconds with {:02d} print(f"{h:02d}h {m:02d}m {s:02d}s") # Outputs '01h 01m 01s'

The humanfriendly library: A formatting friend

Consider humanfriendly if your output will be consumed by non-programmers or where readability is a premium.

from humanfriendly import format_timespan seconds = 3661 print(format_timespan(seconds)) # Outputs: '1 hour and 1 minute'

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:

import timeit # Simply time different methods timeit.timeit("divmod(seconds, 3600)", setup="seconds=3661", number=1000000) timeit.timeit("timedelta(seconds=seconds)", setup="from datetime import timedelta; seconds=3661", number=1000000)

Advanced handling and edge case scenarios

Handling overflow and negative input

Ensure your solution handles negative inputs for an all-encompassing solution.

seconds = -3661 h, m, s = (abs(seconds) // 3600, (abs(seconds) % 3600) // 60, abs(seconds) % 60) neg = "-" if seconds < 0 else "" print(f"{neg}{h:02d}h {m:02d}m {s:02d}s")

Working with large numbers

Python easily handles large numbers, so rest easy when capturing significant timespans.

seconds = 10**12 print(timedelta(seconds=seconds)) # Python doesn't break a sweat!