Skip to content

gh-124549: Warn on conflicting directives in datetime.*.strptime #132524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Doc/library/datetime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2765,6 +2765,15 @@ Notes:
:exc:`DeprecationWarning`. In 3.15 or later we may change this into
an error or change the default year to a leap year. See :gh:`70647`.

(11)
When parsing a string using :meth:`~.datetime.strptime`, if more than one
directive of the same time unit is used, a SyntaxWarning is raised as
only the last directive gets parsed and applied to the datetime object. For
example, if the format string contains both ``%Y`` and ``%y``, like ``%Y%y``,
only the last directive of the string (``%y``) gets used on the resulting
datetime object.


.. rubric:: Footnotes

.. [#] If, that is, we ignore the effects of Relativity
Expand Down
7 changes: 5 additions & 2 deletions Lib/_strptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,12 +357,15 @@ def pattern(self, format):
day_of_month_in_format = False
def repl(m):
format_char = m[1]
nonlocal year_in_format, day_of_month_in_format
match format_char:
case 'Y' | 'y' | 'G':
nonlocal year_in_format
if year_in_format:
import warnings
warnings.warn("When using conflicting directives only the last one will be used.",
SyntaxWarning, skip_file_prefixes=(os.path.dirname(__file__),))
year_in_format = True
case 'd':
nonlocal day_of_month_in_format
day_of_month_in_format = True
return self[format_char]
format = re_sub(r'%([OE]?\\?.?)', repl, format)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Raise a warning in :func:`datetime.datetime.strptime` and :func:`datetime.date.strptime`
when conflicting directives are provided.
Loading