durationpy
durationpy is a Python module designed for converting between Python's `datetime.timedelta` objects and Go's standard `time.Duration` string format. The current version, 0.10, was released on May 17, 2025, and the project demonstrates an active release cadence with several updates in recent years, indicating ongoing maintenance.
Common errors
-
ModuleNotFoundError: No module named 'durationpy'
cause The 'durationpy' library is not installed in your Python environment or is not accessible via the Python path.fixInstall the library using pip: `pip install durationpy` -
ValueError: Invalid duration string format: 'PT10S'
cause The input string provided to `durationpy.from_str()` does not conform to Go's standard `time.Duration` string format, which `durationpy` expects. For example, it does not support ISO 8601 duration strings like 'PT10S'.fixProvide a correctly formatted Go-style duration string (e.g., '10s', '1h30m', '5m2s'). Refer to the `durationpy` documentation for supported units and formats. -
TypeError: argument must be datetime.timedelta, not str
cause An object that is not a `datetime.timedelta` instance (e.g., a string or integer) was passed to a `durationpy` function that expects a `timedelta` object, such as `durationpy.to_str()`.fixEnsure the input argument is a `datetime.timedelta` object. For example, `from datetime import timedelta; durationpy.to_str(timedelta(seconds=10))`.
Warnings
- gotcha Nanosecond precision is lost when parsing Go duration strings that include nanoseconds (e.g., '1ns') because Python's `datetime.timedelta` object natively supports only microsecond resolution.
- gotcha The `durationpy` library is specifically designed to parse Go's `time.Duration` string format (e.g., '1h30m15s'). It will not correctly parse arbitrary human-readable duration strings (e.g., '1 hour and 30 minutes', '2 days, 4 hours'). Incorrect formats will likely raise `ValueError` or return unexpected results.
Install
-
pip install durationpy
Imports
- from_str
from durationpy import from_str
- to_str
from durationpy import to_str
Quickstart
import durationpy
import datetime
# Parse a Go duration string into a datetime.timedelta object
td = durationpy.from_str("4h3m2s1ms")
print(f"Parsed timedelta: {td}")
print(f"Total seconds: {td.total_seconds()}")
# Convert a datetime.timedelta object back to a Go duration string
duration_str = durationpy.to_str(datetime.timedelta(hours=1, minutes=30, seconds=15))
print(f"Formatted duration string: {duration_str}")
# Example demonstrating nanosecond precision loss
td_nano_input = "1h1m1s1ns"
td_nano_parsed = durationpy.from_str(td_nano_input)
print(f"Original Go duration: {td_nano_input}")
print(f"Parsed (nanosecond precision is lost): {td_nano_parsed}")