aniso8601 Library
aniso8601 is a Python library designed for robust parsing of ISO 8601 strings into native Python `datetime` and `timedelta` objects. It supports durations, dates, times, and datetimes, adhering strictly to the ISO 8601 standard. The current version is 10.0.1, and it maintains an active, though irregular, release cadence.
Warnings
- breaking Starting with v9.0.0, the return types for `parse_duration` and `parse_datetime` changed. `parse_duration` now returns `datetime.timedelta` (instead of `aniso8601.Duration`) and `parse_datetime` returns `datetime.datetime` (instead of `aniso8601.DateTime`). Code relying on the specific `aniso8601` custom objects will break.
- breaking In v10.0.0, Python 3.6 support was dropped. Additionally, the `parse_repeating_interval` function was removed entirely, and all exception classes were moved directly under the `aniso8601` package (e.g., `aniso8601.ISO8601Error` instead of `aniso8601.exceptions.ISO8601Error`).
- gotcha aniso8601 is strict about ISO 8601 compliance. It does not attempt to 'guess' or be lenient with non-standard formats. Input strings must strictly conform to the ISO 8601 specification to be parsed successfully. This can lead to unexpected `ISO8601Error` for subtly malformed strings.
- gotcha When parsing datetimes without an explicit timezone offset (e.g., '2023-01-15T10:00:00'), `parse_datetime` will return a naive `datetime` object (i.e., `dt.tzinfo` will be `None`). It does not assume UTC or any local timezone by default for such strings.
Install
-
pip install aniso8601
Imports
- parse_datetime
from aniso8601.parse import parse_datetime
- parse_date
from aniso8601.parse import parse_date
- parse_time
from aniso8601.parse import parse_time
- parse_duration
from aniso8601.parse import parse_duration
- ISO8601Error
from aniso8601 import ISO8601Error
Quickstart
import aniso8601.parse
import datetime
# Parse an ISO 8601 duration string
duration_str = "P3Y6M4DT12H30M5S"
duration = aniso8601.parse.parse_duration(duration_str)
print(f"Parsed Duration: {duration} (Type: {type(duration)})\n")
# Parse an ISO 8601 datetime string with timezone
datetime_str = "2023-01-15T10:00:00+01:00"
dt = aniso8601.parse.parse_datetime(datetime_str)
print(f"Parsed Datetime: {dt} (Type: {type(dt)}, TZ: {dt.tzinfo})\n")
# Parse an ISO 8601 datetime string (UTC)
utc_datetime_str = "2024-03-01T14:30:00Z"
utc_dt = aniso8601.parse.parse_datetime(utc_datetime_str)
print(f"Parsed UTC Datetime: {utc_dt} (Type: {type(utc_dt)}, TZ: {utc_dt.tzinfo})\n")
# Handle potential parsing errors
try:
invalid_str = "invalid-date-string"
aniso8601.parse.parse_datetime(invalid_str)
except aniso8601.ISO8601Error as e:
print(f"Error parsing '{invalid_str}': {e}")