datetime.fromisoformat(date_string) parses an ISO 8601 string and returns a datetime. If the text ends with an offset such as +05:30, the result is aware; otherwise it is naive.
On Python 3.7 to 3.10 it only accepts the formats isoformat() can produce. Python 3.11 accepts most ISO 8601 text, including a trailing Z and compact forms like 20240315T103000. date.fromisoformat() and time.fromisoformat() parse just a date or a time.
datetime.fromisoformat() is a classmethod of datetime.datetime: call it on the class itself, as datetime.fromisoformat(...), and it returns a new object. Import the class first, for example from datetime import datetime. The date and time classes have a method with the same name. Added in Python 3.7.
Syntax
Pass the ISO 8601 text.
python
moment = datetime.fromisoformat(date_string)
day = date.fromisoformat("2024-03-15")
Milliseconds scale up..250 means 250 milliseconds, stored as microsecond=250000.
Offset becomes tzinfo. The +05:30 suffix creates a fixed-offset timezone, so utcoffset() returns 5:30:00.
Convert to UTC. Subtracting 5 hours 30 minutes gives 05:00:45.250 UTC, written back with six fractional digits.
Example 3 — Accept a Trailing Z on Older Pythons
Python 3.11+ parses Z directly. This helper rewrites it to +00:00 so the same code runs on 3.7 to 3.10 too, and reports text that is not ISO 8601.
python
from datetime import datetime
def parse_iso(text):
if text.endswith("Z"):
text = text[:-1] + "+00:00"
return datetime.fromisoformat(text)
for raw in ("2024-03-15T10:30:00Z", "2024-03-15T10:30:00+01:00", "15/03/2024"):
try:
print(parse_iso(raw).isoformat())
except ValueError:
print("not ISO 8601:", raw)
Output
2024-03-15T10:30:00+00:00
2024-03-15T10:30:00+01:00
not ISO 8601: 15/03/2024
How It Works
Z means UTC. The helper swaps the trailing Z for +00:00, which every supported version understands.
Offsets kept.+01:00 parses into an aware datetime and isoformat() writes the same offset back.
Wrong layout. Day/month/year text raises ValueError, which the loop reports instead of crashing.
Frequently Asked Questions
Use datetime.fromisoformat("2024-03-15T10:30:00"). For a date only, use date.fromisoformat("2024-03-15").
Before Python 3.11 the Z suffix was not accepted. Replace it with +00:00 first, or upgrade to 3.11+.
Usually yes, because it parses one fixed grammar instead of interpreting a format string.
Only if the text contains an offset such as +05:30. Otherwise the result is naive.
That is not ISO 8601. Use datetime.strptime(text, "%d/%m/%Y").