Created
September 11, 2025 10:44
-
-
Save evtn/0580d47168af808be15be36a04488bb8 to your computer and use it in GitHub Desktop.
unironically a nice duration formatting function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from dataclasses import dataclass | |
| from typing import Sequence | |
| @dataclass | |
| class TimeUnit: | |
| name: str | |
| size: float = 1 | |
| sep: str = ":" | |
| min_width: int = 2 | |
| SECOND = TimeUnit("s") | |
| MILLISECOND = TimeUnit("ms", SECOND.size / 1000, sep=".") | |
| MINUTE = TimeUnit("m", SECOND.size * 60) | |
| HOUR = TimeUnit("h", MINUTE.size * 60) | |
| DAY = TimeUnit("d", HOUR.size * 24) | |
| def format_duration( | |
| seconds: float, | |
| unit_defs: Sequence[TimeUnit] = (SECOND, MINUTE, HOUR), | |
| use_sep: bool = True, | |
| use_name: bool = False, | |
| min_units: int = 2, | |
| ) -> str: | |
| unit_defs = sorted( | |
| unit_defs, | |
| key=lambda u: u.size, | |
| reverse=True, | |
| ) | |
| result: list[str] = [] | |
| for i, unit in enumerate(unit_defs): | |
| if result and use_sep: | |
| result.append(unit.sep) | |
| value, seconds = divmod(seconds, unit.size) | |
| if not value and i < len(unit_defs) - min_units: | |
| continue | |
| result.append(f"{value:0{unit.min_width}.0f}") | |
| if use_name: | |
| result.append(unit.name) | |
| return "".join(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment