Simple module to parse ISO 8601 dates
This module parses the most common forms of ISO 8601 date strings (e.g., 2007-01-14T20:34:22+00:00) into `datetime` objects. It simplifies the process of converting various ISO 8601 date and time formats into Python's native `datetime` types. The library is actively maintained, with a typical release cadence of a few minor/patch versions per year, ensuring compatibility and bug fixes.
Warnings
- breaking Version 2.0.0 dropped support for Python 3.6. Users on Python 3.6 must remain on `iso8601<2.0.0`.
- breaking Version 1.0.0 dropped support for Python 2.x and required Python 3.6 or newer.
- gotcha The library deviates from the strict ISO 8601 specification by allowing a space character (' ') instead of 'T' as a date-time separator and parsing single-digit days/months without leading zeros (e.g., 'YYYY-M-D').
- gotcha Prior to version 0.1.8, if a date string included 'Z' (indicating UTC), the `default_timezone` parameter might have incorrectly overridden it. From 0.1.8 onwards, 'Z' correctly implies UTC and takes precedence. This was a fix but could be a breaking change if relying on the previous incorrect behavior.
- gotcha If no timezone information is provided in the string, `iso8601` defaults to UTC. If you need naive `datetime` objects for strings without explicit timezone, you must pass `default_timezone=None` to `parse_date`.
Install
-
pip install iso8601
Imports
- parse_date
import iso8601 datetime_obj = iso8601.parse_date('2007-01-25T12:00:00Z')
Quickstart
import iso8601
from datetime import datetime, timezone
# Parse a full ISO 8601 datetime string with UTC timezone
datetime_str_utc = '2023-10-27T10:00:00Z'
datetime_obj_utc = iso8601.parse_date(datetime_str_utc)
print(f"Parsed UTC: {datetime_obj_utc}")
assert datetime_obj_utc == datetime(2023, 10, 27, 10, 0, tzinfo=timezone.utc)
# Parse a datetime string with an offset timezone
datetime_str_offset = '2023-10-27T10:00:00-05:00'
datetime_obj_offset = iso8601.parse_date(datetime_str_offset)
print(f"Parsed Offset: {datetime_obj_offset}")
# Parse a date-only string (time defaults to 00:00:00 UTC)
date_str = '2023-10-27'
datetime_obj_date_only = iso8601.parse_date(date_str)
print(f"Parsed Date Only: {datetime_obj_date_only}")
assert datetime_obj_date_only == datetime(2023, 10, 27, 0, 0, tzinfo=iso8601.UTC)
# Parse a date with a space separator instead of 'T'
datetime_str_space = '2023-10-27 10:00:00+01:00'
datetime_obj_space = iso8601.parse_date(datetime_str_space)
print(f"Parsed with Space: {datetime_obj_space}")