Dates arrive as text from CSV files, forms, logs and APIs.
For ISO 8601 strings, use fromisoformat. Since Python 3.11 it accepts most ISO formats, including a trailing Z for UTC, offsets like +05:30, T or space separators, fractional seconds and basic formats like 20250301:
datetime.fromisoformat("2025-03-01T14:30:00Z") # aware, UTCIt's fast and strict, which is exactly what you want for machine data.
For other formats, use strptime ("string parse time") with the same codes as strftime. The format must match the whole string exactly, including separators:
datetime.strptime("01/03/2025 14:30", "%d/%m/%Y %H:%M")A mismatch raises ValueError with a message showing the data and format, so wrap parsing of untrusted input in try/except.
Watch out for:
- Ambiguous formats:
03/01/2025is March 1 in the US and January 3 elsewhere. Know your source. %zparses+0100,+01:00andZ, producing an aware datetime; without it the result is naive.%Zmatches only a few names (UTC, GMT, local zone names) and doesn't attach a time zone.date.fromisoformatandtime.fromisoformatexist for the separate types;datetime.strptime(...).date()works for dates in custom formats.
For free-form or messy dates, the third-party dateutil.parser is more forgiving.
Example
from datetime import datetime
a = datetime.fromisoformat("2025-03-01T14:30:00Z")
print(a, a.tzinfo) # 2025-03-01 14:30:00+00:00 UTC
print(datetime.fromisoformat("2025-03-01 14:30:00.5+05:30"))
# 2025-03-01 14:30:00.500000+05:30
print(datetime.fromisoformat("20250301")) # 2025-03-01 00:00:00
b = datetime.strptime("01/03/2025 2:30 PM", "%d/%m/%Y %I:%M %p")
print(b) # 2025-03-01 14:30:00
c = datetime.strptime("Mar 1 2025 +0100", "%b %d %Y %z")
print(c.utcoffset()) # 1:00:00
try:
datetime.strptime("2025-03-01", "%d/%m/%Y")
except ValueError as e:
print(e) # time data '2025-03-01' does not match format '%d/%m/%Y'Remember
fromisoformatparses ISO 8601, including 'Z', since 3.11strptimeneeds a format that matches the whole string exactly- Use
%zto get an aware datetime; beware ambiguous day/month orders
Watch out for
- Parsing ISO strings with a hand-written strptime format that breaks on fractional seconds or a 'Z' suffix.