Skip to content

Commit d87b20a

Browse files
committed
gh-70647: Better promote how to safely parse yearless dates in datetime.
Every four years people encounter this because it just isn't obvious. This moves the footnote up to a note with a code example. We'd love to change the default year value for datetime but doing that could have other consequences for existing code. This documented workaround *always* works.
1 parent de0b4f9 commit d87b20a

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

Doc/library/datetime.rst

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2525,7 +2525,24 @@ Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
25252525

25262526
For the :meth:`.datetime.strptime` class method, the default value is
25272527
``1900-01-01T00:00:00.000``: any components not specified in the format string
2528-
will be pulled from the default value. [#]_
2528+
will be pulled from the default value.
2529+
2530+
.. note::
2531+
When used to parse partial dates lacking a year, :meth:`~.datetime.strptime`
2532+
will raise when encountering February 29 because its default year of 1900 is
2533+
*not* a leap year. Always add a default leap year to partial date strings
2534+
before parsing::
2535+
2536+
.. doctest::
2537+
2538+
>>> from datetime import datetime
2539+
>>> value = "2/29"
2540+
>>> datetime.strptime(value, "%m/%d")
2541+
Traceback (most recent call last):
2542+
...
2543+
ValueError: day is out of range for month
2544+
>>> datetime.strptime(f"1904 {value}", "%Y %m/%d")
2545+
datetime.datetime(1904, 2, 29, 0, 0)
25292546

25302547
Using ``datetime.strptime(date_string, format)`` is equivalent to::
25312548

@@ -2651,6 +2668,11 @@ Notes:
26512668
for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, ``%j``, ``%U``,
26522669
``%W``, and ``%V``. Format ``%y`` does require a leading zero.
26532670

2671+
(10)
2672+
Parsing dates without a year using :meth:`~.datetime.strptime` will fail on
2673+
representations of February 29 as that date does not exist in the default
2674+
year of 1900.
2675+
26542676
.. rubric:: Footnotes
26552677

26562678
.. [#] If, that is, we ignore the effects of Relativity
@@ -2664,5 +2686,3 @@ Notes:
26642686
.. [#] See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar
26652687
<https://web.archive.org/web/20220531051136/https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm>`_
26662688
for a good explanation.
2667-
2668-
.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year.

0 commit comments

Comments
 (0)