C.W.K.
Stream
Lesson 04 of 12 · published

Date and Time Patterns

~8 min · date, time, iso8601

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

ISO 8601 — the canonical format

Always prefer YYYY-MM-DD and ISO 8601 timestamps when you control the format. The regex is trivial:

  • Date: \d{4}-\d{2}-\d{2}
  • Time: \d{2}:\d{2}:\d{2}
  • Datetime: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?

Common ambiguous formats

05/04/2026: is this May 4 (US) or April 5 (most of the world)? Regex can't tell. Don't accept ambiguous formats. Force ISO 8601, or accept multiple unambiguous formats explicitly.

If you must parse various formats, write multiple patterns and try each in order:

1. ISO: \d{4}-\d{2}-\d{2}
2. US slash: \d{1,2}/\d{1,2}/\d{4}
3. EU dot: \d{1,2}\.\d{1,2}\.\d{4}
4. Long: (Jan|Feb|...)\s+\d{1,2},?\s+\d{4}

Validation vs parsing

Regex tells you the SHAPE matches. It doesn't tell you the date is REAL. 2026-02-30 matches the pattern but Feb 30 doesn't exist. Real validation: datetime.strptime(s, fmt) in Python, new Date(s) in JS (then check !isNaN), time.Parse in Go.

Extracting dates from prose

For "find dates in this paragraph," use anchored alternation: \b(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\b. Be conservative — false positives in date extraction are common.

Code

Date patterns·python
import re
from datetime import datetime

# ISO date validation
DATE_ISO = re.compile(r'^\d{4}-\d{2}-\d{2}$')
bool(DATE_ISO.fullmatch('2026-05-04'))   # True
bool(DATE_ISO.fullmatch('2026/05/04'))   # False

# Validate AND parse
def parse_iso_date(s):
    if not DATE_ISO.fullmatch(s):
        return None
    try:
        return datetime.strptime(s, '%Y-%m-%d').date()
    except ValueError:
        return None  # caught Feb 30 and similar

parse_iso_date('2026-05-04')  # date(2026, 5, 4)
parse_iso_date('2026-02-30')  # None — shape OK, value invalid

# Full ISO datetime with timezone
DT_ISO = re.compile(
    r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$'
)
bool(DT_ISO.fullmatch('2026-05-04T14:32:11Z'))            # True
bool(DT_ISO.fullmatch('2026-05-04T14:32:11.123+09:00'))   # True

# Find dates in prose
DATE_FIND = re.compile(r'\b\d{4}-\d{2}-\d{2}\b')
re.findall(DATE_FIND, 'logged on 2026-05-04 and 2026-05-05')
# ['2026-05-04', '2026-05-05']

External links

Exercise

Take a date pattern from your code. Test it against 2026-13-01 and 2026-02-30. The first is invalid month, the second invalid day. Does your regex catch them, or does the actual datetime.strptime call do the work? Decide whether the regex needs to be stricter or whether validation is enough.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.