Conservative rendering and liberal parsing of ISO 8601 timestamps in Python
Contents
You’ll see in Python bug 37962 that datetime.isoformat()
and
datetime.fromisoformat()
use a restricted subset of the ISO 8601 timestamp
formatting standards.
This is similar to the subset followed by W3C.
Recently, we ran into the specific issue that fromisoformat()
rejects inputs
where the timezone is specified as +hhmm
instead of +hh:mm
.
Both are allowed by ISO 8601, but only the latter is part of the restricted subset.
Following the Robustness principle (also known as Postel’s law) in the design of our APIs, we would prefer to
Be liberal in what you accept, and conservative in what you send.
Fortunately, the dateutil package’s parser.isoparse()
is able to parse a
broader subset of the standard.
Based on this and the bug report linked above, consider the following guideline:
Default to formatting Python timestamps with
datetime.isoformat()
, but parse incoming timestamps withdateutil.parser.isoparse()
.