这是indexloc提供的服务,不要输入任何密码
Skip to content

strptime: use %r in error messages, not %s #141540

@alexwlchan

Description

@alexwlchan

Bug report

Bug description:

Consider the following example, say I'm parsing a date string read from an external source, and I forgot to call .strip():

from datetime import datetime

datetime.strptime("2001-02-03\n", "%Y-%m-%d")

The output is a little confusing:

$ python3 strptime_example.py
Traceback (most recent call last):
  File "strptime_example.py", line 3, in <module>
    datetime.strptime("2025-11-14\n", "%Y-%m-%d")
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/_strptime.py", line 789, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/_strptime.py", line 558, in _strptime
    raise ValueError("unconverted data remains: %s" %
                      data_string[found.end():])
ValueError: unconverted data remains: 

The error message is using %s, when using %r would give a more unambiguous description of the extra data – similar with strings quoted manually using ' in the error message just above:

cpython/Lib/_strptime.py

Lines 567 to 570 in a486d45

raise ValueError(
f"Missing colon in %:z before '{rest}', got '{data_string}'"
)
raise ValueError("unconverted data remains: %s" % rest)

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions