Skip to content

Commit eb63f10

Browse files
Raise a warning when passing conflicting directives
Co-authored-by: Mariatta <Mariatta@users.noreply.github.com>
1 parent 1e5798e commit eb63f10

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

Doc/library/datetime.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2765,6 +2765,15 @@ Notes:
27652765
:exc:`DeprecationWarning`. In 3.15 or later we may change this into
27662766
an error or change the default year to a leap year. See :gh:`70647`.
27672767

2768+
(11)
2769+
When parsing a string using :meth:`~.datetime.strptime`, if more than one
2770+
directives of the same time unit were used, a SyntaxWarning is raised as
2771+
only the last directive gets parsed and applied to the datetime object. For
2772+
example, if the format string contains both ``%Y`` and ``%y``, like ``%Y%y``,
2773+
only the last directive on the string (``%y``) gets used on the resulting
2774+
datetime object.
2775+
2776+
27682777
.. rubric:: Footnotes
27692778

27702779
.. [#] If, that is, we ignore the effects of Relativity

Lib/_strptime.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,12 +357,15 @@ def pattern(self, format):
357357
day_of_month_in_format = False
358358
def repl(m):
359359
format_char = m[1]
360+
nonlocal year_in_format, day_of_month_in_format
360361
match format_char:
361362
case 'Y' | 'y' | 'G':
362-
nonlocal year_in_format
363+
if year_in_format:
364+
import warnings
365+
warnings.warn("When using conflicting directives only the last one will be used.",
366+
SyntaxWarning, skip_file_prefixes=(os.path.dirname(__file__),))
363367
year_in_format = True
364368
case 'd':
365-
nonlocal day_of_month_in_format
366369
day_of_month_in_format = True
367370
return self[format_char]
368371
format = re_sub(r'%([OE]?\\?.?)', repl, format)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Raise a warning in :func:`datetime.datetime.strptime` and :func:`datetime.date.strptime`
2+
when conflicting directives are provided.

0 commit comments

Comments
 (0)