Format a duration without calling it a wall-clock time

Format a duration without calling it a wall-clock time

A timedelta is an elapsed amount, not a time of day. Labeling an elapsed value such as 26 hours as 02:00 would silently discard the day component and make it look like a wall-clock reading. This example deliberately formats total hours, so one day, two hours, three minutes, and four seconds becomes 26:03:04.

abs(value) makes component extraction straightforward, while the separately recorded sign keeps negative output readable. Dividing a timedelta by a one-second timedelta with // produces an integer count of complete seconds; consecutive divmod calls then split that count into hours, minutes, and seconds. The assertions cover both a duration longer than a day and a negative duration. The printed strings are labels for elapsed time, not timezone-aware timestamps and not evidence of when anything happened.

This formatter truncates sub-second values rather than rounding them. It also intentionally uses hours beyond 23; choose a different display contract if readers need days shown separately, localization, or fractional seconds. timedelta represents a duration to microsecond resolution, and its arithmetic normalization can make its default string form awkward for negative values. The standard library documents both the duration model and that caveat. Python timedelta documentation

AI-assistance disclosure: AI helped draft this educational example; its assertions are limited to the stated sample values.

from datetime import timedelta


def format_duration(value):
    sign = "-" if value < timedelta() else ""
    whole_seconds = abs(value) // timedelta(seconds=1)
    hours, remainder = divmod(whole_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{sign}{hours:02}:{minutes:02}:{seconds:02}"


long_elapsed = timedelta(days=1, hours=2, minutes=3, seconds=4)
negative_elapsed = -timedelta(minutes=5, seconds=6)

assert format_duration(long_elapsed) == "26:03:04"
assert format_duration(negative_elapsed) == "-00:05:06"

print(format_duration(long_elapsed))
print(format_duration(negative_elapsed))
26:03:04
-00:05:06

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic