Python

Format Bytes / Duration Human-Readable

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Two formatting helpers everyone re-implements: bytes → "1.5 MB", seconds → "1h 23m 45s". Base-1024 IEC units by default for bytes.
Python
Raw
def human_bytes(n: int, precision: int = 1, base: int = 1024) -> str:
    units = ("B", "KiB", "MiB", "GiB", "TiB", "PiB") if base == 1024 \
       else ("B", "kB", "MB", "GB", "TB", "PB")
    if n <= 0:
        return "0 B"
    i, n_f = 0, float(n)
    while n_f >= base and i < len(units) - 1:
        n_f /= base
        i += 1
    return f"{n_f:.{precision}f} {units[i]}"

def human_duration(seconds: int) -> str:
    if seconds < 0:
        return "-" + human_duration(-seconds)
    parts = []
    for label, size in (("d", 86_400), ("h", 3_600), ("m", 60), ("s", 1)):
        if seconds >= size:
            n, seconds = divmod(seconds, size)
            parts.append(f"{n}{label}")
    return " ".join(parts) or "0s"

print(human_bytes(1_536_000_000))            # 1.4 GiB
print(human_duration(3_725))                 # 1h 2m 5s
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.