File size: 793 Bytes
da6ee5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""Date parsing helpers."""

from __future__ import annotations

from datetime import datetime
from typing import Any

_DATE_FORMATS = ("%Y-%m-%d", "%d/%m/%Y", "%d.%m.%Y")


def parse_date(value: Any) -> datetime | None:
    """Parse common ISO / EU date strings."""
    if not value or not isinstance(value, str):
        return None
    raw = value.strip()[:10]
    for fmt in _DATE_FORMATS:
        try:
            return datetime.strptime(raw, fmt)
        except ValueError:
            continue
    return None


def to_iso_date(value: str | None) -> str | None:
    """Normalize a date string to YYYY-MM-DD when possible."""
    if not value:
        return None
    parsed = parse_date(value)
    if parsed is None:
        return value.strip()
    return parsed.strftime("%Y-%m-%d")