durationpy
Convert between Python timedelta and Go time.Duration strings
Repository Health
Technical Analysis
durationpy is a small, focused Python library that converts between datetime.timedelta objects and Go-style duration strings such as 4h3m2s1ms. It parses a compact duration expression into a timedelta and formats a timedelta back into the same string syntax, bridging Python and Go representations of time spans.
It understands units from nanoseconds up to years (ns, us, ms, s, m, h, d, w, mm, y), handles signed values, and raises a clear DurationError on malformed input. The whole surface is two functions — from_str and to_str — making it a lightweight dependency for config parsing and interop with Go services.
What You Get
from_str()to parse a Go-style duration string into adatetime.timedeltato_str()to format atimedeltaback into a Go duration string- Support for units from nanoseconds through years, including signed values
- A
DurationError(subclass ofValueError) raised on invalid input - Type hints via a shipped
py.typedmarker for static checkers
Common Use Cases
- Parsing Go-style duration values from configuration files or environment variables
- Interoperating with Go services or Kubernetes manifests that use
time.Durationstrings - Rendering a Python
timedeltain Go’s compact duration syntax - Reading and writing durations in a format shared between Python and Go codebases
Under The Hood
Architecture - The entire library is a single module, durationpy/duration.py. A units dict maps unit suffixes to nanosecond sizes, a compiled regex _duration_re tokenizes the input into number/unit pairs, and from_str sums the matched components (after sign handling and boundary validation) into a datetime.timedelta; to_str performs the inverse, decomposing a timedelta into the largest applicable units. Nanosecond precision is intentionally lossy because timedelta resolves to microseconds.
Tech Stack - Pure Python with no third-party runtime dependencies — only the standard re and datetime modules. Packaging is a classic setup.py/setup.cfg with a py.typed marker and a .pyi stub for typing.
Code Quality - The code is compact and readable, with a dedicated DurationError for failure cases and explicit validation that rejects extra characters at the string boundaries. A test.py suite covers the round-trip parsing and formatting behavior. Activity is low, but the scope is small and stable.
API Design - The public API is deliberately minimal — two functions with obvious names — so there is essentially no learning curve. The README documents every supported unit and shows a parse/format example, and matching Go’s well-known duration syntax makes behavior predictable for anyone coming from that ecosystem.