Converting Seconds to Days, Hours, Minutes, and Seconds in Python

When calculating time differences, Python's datetime module returns a timedelta object. For example:

import datetime

start = datetime.datetime(2021, 1, 1)
delta = datetime.datetime.now() - start
print(delta)  # Example: 150 days, 11:20:06.749774
print(delta.days)   # 150
print(delta.seconds)  # 40806

While timedelta conveniently provides days and seconds attributes, the output can be unfriendly for human readability. To gain full control, convert the entire interval to seconds using total_seconds():

total_sec = delta.total_seconds()  # Example: 13000936.085446

Once you have total seconds, you can decompose them into days, hours, minutes, and seconds with a custom function. The following implementation handles singular and plural forms properly:

def decompose_seconds(total_seconds):
    # Extract components
    days = total_seconds // (24 * 3600)
    remaining = total_seconds % (24 * 3600)
    hours = remaining // 3600
    remaining %= 3600
    minutes = remaining // 60
    seconds = remaining % 60

    # Build label conditionally
    parts = []
    if days > 0:
        label = "day" if days == 1 else "days"
        parts.append(f"{int(days)} {label}")
    if hours > 0:
        label = "hour" if hours == 1 else "hours"
        parts.append(f"{int(hours)} {label}")
    if minutes > 0:
        label = "minute" if minutes == 1 else "minutes"
        parts.append(f"{int(minutes)} {label}")
    if seconds > 0 or not parts:  # Include seconds if present or if all others are zero
        label = "second" if seconds == 1 else "seconds"
        parts.append(f"{int(seconds)} {label}")

    return ", ".join(parts[:-1]) + " and " + parts[-1] if len(parts) > 1 else parts[0]

Test the function with various inputs:

# Example 1: 1 day, 1 minute, 2 seconds
print(decompose_seconds(86400 + 60 + 2))  # Output: 1 day, 1 minute and 2 seconds

# Example 2: 45 days, 13 minutes, 59 seconds
test = 45 * 24 * 3600 + 13 * 60 + 59
print(decompose_seconds(test))  # Output: 45 days, 13 minutes and 59 seconds

# Example 3: 45 days, 47 minutes, 59 seconds
test = 45 * 24 * 3600 + (13 + 34) * 60 + 59
print(decompose_seconds(test))  # Output: 45 days, 47 minutes and 59 seconds

# Example 4: 46 days, 10 hours, 13 minutes, 59 seconds
test = 45 * 24 * 3600 + 13 * 60 + 59 + 34 * 3600
print(decompose_seconds(test))  # Output: 46 days, 10 hours, 13 minutes and 59 seconds

# Example 5: 45 days, 14 hours, 13 minutes, 59 seconds
test = 45 * 24 * 3600 + 13 * 60 + 59 + 14 * 3600
print(decompose_seconds(test))  # Output: 45 days, 14 hours, 13 minutes and 59 seconds

The function automatically drops zero-valued components (unless all components are zero, in which case it shows "0 seconds"). For a Chinese localizatino, you can simpliyf the function by directly formatting the string with fixed labels.

Tags: python datetime time-conversion

Posted on Fri, 23 Oct 2026 16:09:16 +0000 by mgallforever