Backport of datetime.fromisoformat
This library provides a backport of Python 3.11's extended `datetime.fromisoformat` functionality to older Python versions (prior to 3.11). It allows parsing a wider range of ISO 8601 formatted strings, including those with timezone offsets using colons and fractional seconds. The current version is 2.0.3, with releases occurring on an as-needed basis to address compatibility or new Python version changes.
Warnings
- gotcha This library relies on monkey-patching. The `datetime.fromisoformat` method will only be extended if `backports.datetime_fromisoformat` is imported *after* the `datetime` module.
- breaking Version 2.0.0 changed the underlying logic for the backported `fromisoformat` methods. Prior to 2.0.0, it backported Python 3.7's logic; from 2.0.0 onwards, it backports Python 3.11's logic, supporting a wider range of ISO 8601 formats.
- gotcha This library is designed for Python versions older than 3.11. Installing and importing it on Python 3.11 or newer has no effect on `datetime.fromisoformat` and adds unnecessary overhead.
Install
-
pip install "backports-datetime-fromisoformat; python_version < '3.11'" -
pip install backports-datetime-fromisoformat
Imports
- datetime.fromisoformat
import datetime import backports.datetime_fromisoformat
Quickstart
import datetime
import backports.datetime_fromisoformat
# This string would fail on Python < 3.11 without the backport due to the colon in the timezone offset
isodate_str = "2023-10-27T10:00:00.123456+05:30"
try:
dt_object = datetime.datetime.fromisoformat(isodate_str)
print(f"Successfully parsed: {dt_object}")
print(f"Type: {type(dt_object)}")
except ValueError as e:
print(f"Error parsing date: {e}")