10000 [3.12] gh-70647: update docs to mention the datetime 1900 year defaul… · python/cpython@3eb7a90 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3eb7a90

Browse files
authored
[3.12] gh-70647: update docs to mention the datetime 1900 year default 2/29 issue (#131534)
* 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. * doctest code within note is bad, dedent.
1 parent e1626c3 commit 3eb7a90

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
@@ -2526,7 +2526,24 @@ Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
25262526

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

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

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

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

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

0 commit comments

Comments
 (0)
0