Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | 2023-... |
\d{4} |
Exactly 4 digits (year) | 2023 |
- |
Literal hyphen character | - |
\d{1,2} |
1 or 2 digits (month) | 01 |
- |
Literal hyphen character | - |
\d{1,2} |
1 or 2 digits (day) | 15 |
T |
Literal 'T' character (ISO 8601 separator) | T |
\d{1,2} |
1 or 2 digits (hour in 24-hour format) | 14 |
: |
Literal colon character | : |
\d{2} |
Exactly 2 digits (minutes) | 30 |
: |
Literal colon character | : |
\d{2} |
Exactly 2 digits (seconds) | 45 |
(?:\.\d{1,6})? |
Non-capturing group: optional fractional seconds (1-6 digits) | .123456 |
(?:Z|[+-]\d{2}:?\d{2}) |
Non-capturing group: 'Z' or timezone offset (+/-HH:MM or +/-HHMM) | Z or +05:30 |
$ |
Anchor: asserts position at end of the string | ...00Z |
Matches
2023-01-15T14:30:45Z2023-12-31T23:59:59+05:302023-02-28T00:00:00-08002023-07-04T12:00:00.123456-04:001999-12-31T23:59:59.9Z
Does not match
2023-1-15T14:30:45Z2023-01-5T14:30:45Z2023-01-15T14:30:452023-01-15T14:30:45.1234567Z2023-01-15T14:30:45+5:302023-01-15T14:30:45Z2023-01-15T14:30:45Z
Common pitfalls
- Forgetting to escape backslashes in Python strings (use raw strings: r'...').
- Assuming the pattern matches all valid ISO 8601 formats (e.g., week-based dates like '2023-W01-1' are not matched).
- Overlooking that the timezone offset must be exactly 2 digits for hours and minutes (e.g., '+5:30' fails).
- Not accounting for the optional fractional seconds (e.g., '2023-01-15T14:30:45Z' is valid).
- Assuming the pattern matches dates before 1000 AD or after 9999 AD (year is exactly 4 digits).
Performance notes
The pattern is linear in complexity (no nested quantifiers or backtracking risks) and is efficient for typical use cases. Anchors (^ and $) ensure no partial matches, improving reliability.