{"record":{"id":"621b2926b9c27d16","repo":"python/cpython","slug":"time-data-r-does-not-match-format-r","errorCode":null,"errorMessage":"time data %r does not match format %r","messagePattern":"time data %r does not match format %r","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Lib/_strptime.py","lineNumber":574,"sourceCode":"        format_regex = _regex_cache.get(format)\n        if not format_regex:\n            try:\n                format_regex = _TimeRE_cache.compile(format)\n            # KeyError raised when a bad format is found; can be specified as\n            # \\\\, in which case it was a stray % but with a space after it\n            except KeyError as err:\n                bad_directive = err.args[0]\n                del err\n                bad_directive = bad_directive.replace('\\\\s', '')\n                if not bad_directive:\n                    raise ValueError(\"stray %% in format '%s'\" % format) from None\n                bad_directive = bad_directive.replace('\\\\', '', 1)\n                raise ValueError(\"'%s' is a bad directive in format '%s'\" %\n                                    (bad_directive, format)) from None\n            _regex_cache[format] = format_regex\n    found = format_regex.match(data_string)\n    if not found:\n        raise ValueError(\"time data %r does not match format %r\" %\n                         (data_string, format))\n    if len(data_string) != found.end():\n        rest = data_string[found.end():]\n        # Specific check for '%:z' directive\n        if (\n            \"colon_z\" in found.re.groupindex\n            and found.group(\"colon_z\") is not None\n            and rest[0] != \":\"\n        ):\n            raise ValueError(\n                f\"Missing colon in %:z before '{rest}', got '{data_string}'\"\n            )\n        raise ValueError(\"unconverted data remains: %s\" % rest)\n\n    iso_year = year = None\n    month = day = 1\n    hour = minute = second = fraction = 0\n    tz = -1","sourceCodeStart":556,"sourceCodeEnd":592,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_strptime.py#L556-L592","documentation":"After compiling the format into a regex, _strptime runs format_regex.match(data_string); if the match fails entirely, this ValueError reports both the data and the format with %r reprs. It means the input string does not fit the format at the very first mismatching position.","triggerScenarios":"datetime.strptime('2020-1-2', '%Y-%m-%d') can pass but '01-02-2020' with '%Y-%m-%d' fails; any case where literals, order, or directive values differ between data and format, e.g. strptime('12/31/99', '%Y-%m-%d') or 24-hour '25:00' with '%H'.","commonSituations":"Mixed source data (US vs ISO date order), zero-padded vs non-padded numbers, locale-dependent month names, AM/PM strings with %H, trailing whitespace/newline in the input.","solutions":["Compare the reprs in the message to spot the first divergent field and fix the format (or the data)","Strip the input: data.strip() before parsing","For variable formats, try datetime.fromisoformat or dateutil.parser","Normalize the input first (e.g. zfill parts, or re.split on separators)"],"exampleFix":"# before\n>>> datetime.strptime('01-02-2020', '%Y-%m-%d')\nValueError: time data '01-02-2020' does not match format '%Y-%m-%d'\n\n# after\n>>> datetime.strptime('01-02-2020', '%d-%m-%Y')\ndatetime.datetime(2020, 2, 1, 0, 0)","handlingStrategy":"fallback","validationCode":"from datetime import datetime\n\ndef try_parse(s: str, fmts):\n    for f in fmts:\n        try:\n            return datetime.strptime(s.strip(), f)\n        except ValueError:\n            continue\n    raise ValueError(f'unparseable date: {s!r}')","typeGuard":null,"tryCatchPattern":"for fmt in ('%Y-%m-%d', '%d/%m/%Y', '%m/%d/%Y'):\n    try:\n        dt = datetime.strptime(s.strip(), fmt)\n        break\n    except ValueError:\n        continue\nelse:\n    raise ValueError(f'unparseable: {s!r}')","preventionTips":["Normalize inputs (strip whitespace/newlines) before parsing","Validate incoming data at the boundary (schema/regex) instead of trusting format alignment","Prefer datetime.fromisoformat for ISO inputs; dateutil.parser for messy ones"],"tags":["strptime","datetime","parsing","format-mismatch","cpython"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}