openai/openai-python · error · ValueError

invalid date format

Error message

invalid date format

What it means

parse_date matches the input string against a strict date regex (ISO-8601 calendar date). This ValueError fires when the string does not match that pattern at all — wrong separators, locale formats, or a full datetime string passed to a date-only field. It is the regex-miss branch, distinct from the second 'invalid date format' raised when the regex matched but the components form an impossible date.

Source

Thrown at src/openai/_utils/_datetime_parse.py:129

    Raise ValueError if the input isn't well formatted.
    """
    if isinstance(value, date):
        if isinstance(value, datetime):
            return value.date()
        else:
            return value

    number = _get_numeric(value, "date")
    if number is not None:
        return _from_unix_seconds(number).date()

    if isinstance(value, bytes):
        value = value.decode()

    assert not isinstance(value, (float, int))
    match = date_re.match(value)
    if match is None:
        raise ValueError("invalid date format")

    kw = {k: int(v) for k, v in match.groupdict().items()}

    try:
        return date(**kw)
    except ValueError:
        raise ValueError("invalid date format") from None

View on GitHub (pinned to 9917c6e28e)

Solutions

  1. Convert the value to an ISO-8601 date string (date.isoformat()) or a datetime.date object before assignment
  2. If the source is a datetime string, truncate it: value[:10] or parse with datetime.fromisoformat(...).date()
  3. Validate with datetime.strptime(value, '%Y-%m-%d') before passing
  4. Add unit fixtures that use strict YYYY-MM-DD strings

Example fix

# before
m = MyModel(expires="03/15/2024")

# after
from datetime import date
m = MyModel(expires=date(2024,3,15).isoformat())
Defensive patterns

Strategy: validation

Validate before calling

from datetime import datetime
try:
    datetime.strptime(value, "%Y-%m-%d")
    ok = True
except ValueError:
    ok = False

Type guard

import re
def is_iso_date(v: str) -> bool:
    return bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", v)) and not "T" in v

Try / catch

try:
    parse_date(s)
except ValueError:
    s = datetime.fromisoformat(s).date().isoformat()  # handle datetime strings

Prevention

When it happens

Trigger: Passing strings like '01/02/2024', '2024-1-5' (unpadded), 'Jan 5, 2024', or '2024-01-05T10:00:00Z' (a datetime string) to a field parsed with parse_date.

Common situations: Hand-building SDK models from user input or CSV/Excel exports with locale-formatted dates; frontend sending datetime strings to date-only fields; tests with sloppy fixtures.

Related errors


AI-assisted analysis of openai/openai-python@9917c6e28e (2026-08-28). Data as JSON: /api/errors/b7a014256cbd0499. Report an issue: GitHub.