Parse and Format Explicit Date Contracts
Core idea
Use date.fromisoformat or datetime.fromisoformat for supported ISO-style strings. strptime parses with a stated format; strftime formats a date or datetime with directives such as %Y, %m and %d. A numeric offset in a string is not a named timezone with its future rules.
from datetime import datetimeparsed = datetime.strptime("25/04/2024", "%d/%m/%Y")print(parsed.date().isoformat())The explicit format disambiguates the order of the fields.
Parse and convert an offset
from datetime import datetime, timezonevalue = datetime.fromisoformat("2024-06-01T08:30:00+02:00")print(value.astimezone(timezone.utc).isoformat())The offset is sufficient to identify this instant.
Common mistake
Invalid dates raise ValueError. Do not infer day-month ordering from ambiguous text. strptime is not always a strict width validator; validate the shape separately if needed. Avoid locale-dependent month names in interchange formats.
Practice
Parse valid date strings using %d/%m/%Y and try an invalid February date; report the ValueError instead of correcting the input silently.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Date format contracts
Check your understanding of parsing and formatting.
What is printed?
from datetime import datetimeprint(datetime.strptime("03/08/2024","%d/%m/%Y").date())What is printed?
from datetime import datetimea=datetime.fromisoformat("2024-01-01T12:00:00+02:00")print(a.strftime("%H:%M %z"))Which exception signals an invalid Gregorian date in strptime?
What does a numeric offset fail to describe?