isoduration
isoduration is a Python library for working with ISO 8601 durations (e.g., 'P3Y6M4DT12H30M5S'). It provides functionality for parsing duration strings, formatting durations, and performing arithmetic operations with Python's `datetime` objects. The library is currently at version 20.11.0, released in 2020, and appears to be in maintenance mode with no recent major releases, though minor updates or repackaging may occur.
Warnings
- gotcha ISO 8601 durations that include years or months represent variable-length periods (e.g., '1 month' can be 28, 29, 30, or 31 days). Python's `datetime.timedelta` is designed for fixed-length durations. `isoduration` addresses this by returning its own `Duration` object for such cases, which correctly handles arithmetic with `datetime` objects.
- gotcha The library had its initial and only PyPI release (20.11.0) in November 2020. While the GitHub repository shows some minor activity in 2021, there haven't been subsequent PyPI releases, suggesting limited active development or a stable, feature-complete state.
- gotcha The `Duration` object's internal components (years, months, days, etc.) are stored as `Decimal` types for precision. Direct comparison or conversion to `datetime.timedelta` (especially for years/months) needs careful handling due to the inherent ambiguity of these units.
Install
-
pip install isoduration
Imports
- parse_duration
from isoduration import parse_duration
- Duration
from isoduration import Duration
Quickstart
from datetime import datetime
from isoduration import parse_duration
# Parse an ISO 8601 duration string
duration_str = "P3Y6M4DT12H30M5S"
duration = parse_duration(duration_str)
print(f"Parsed duration: {duration}")
print(f"Years: {duration.date.years}, Months: {duration.date.months}")
print(f"Hours: {duration.time.hours}, Seconds: {duration.time.seconds}")
# Add the duration to a datetime object
start_time = datetime(2023, 1, 1, 10, 0, 0)
end_time = start_time + duration
print(f"Start time: {start_time}")
print(f"End time after adding duration: {end_time}")
# Negate a duration
negative_duration = -duration
print(f"Negative duration: {negative_duration}")