diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6b6074be0a5728..374dc8046a7822 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -418,6 +418,7 @@ Lib/test/test_dataclasses/ @ericvsmith
# Dates and times
Doc/**/*time.rst @pganssle @abalkin
+Doc/library/datetime-* @pganssle
Doc/library/zoneinfo.rst @pganssle
Include/datetime.h @pganssle @abalkin
Include/internal/pycore_time.h @pganssle @abalkin
diff --git a/Doc/library/datetime-inheritance.dot b/Doc/library/datetime-inheritance.dot
new file mode 100644
index 00000000000000..3c6b9b4beb7ab1
--- /dev/null
+++ b/Doc/library/datetime-inheritance.dot
@@ -0,0 +1,31 @@
+// Used to generate datetime-inheritance.svg with Graphviz
+// (https://graphviz.org/) for the datetime documentation.
+
+digraph {
+ comment="Generated with datetime-inheritance.dot"
+ graph [
+ bgcolor="transparent"
+ fontnames="svg"
+ layout="dot"
+ ranksep=0.5
+ nodesep=0.5
+ splines=line
+ ]
+ node [
+ fontname="Courier"
+ fontsize=14.0
+ shape=box
+ style=rounded
+ margin="0.15,0.07"
+ ]
+ edge [
+ arrowhead=none
+ ]
+
+ object -> tzinfo
+ object -> timedelta
+ object -> time
+ object -> date
+ tzinfo -> timezone
+ date -> datetime
+}
diff --git a/Doc/library/datetime-inheritance.svg b/Doc/library/datetime-inheritance.svg
new file mode 100644
index 00000000000000..e6b1cf877a574f
--- /dev/null
+++ b/Doc/library/datetime-inheritance.svg
@@ -0,0 +1,84 @@
+
+
+
+
+
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 3ab3450032abe4..18cbebe23dd772 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -12,8 +12,6 @@
--------------
-.. XXX what order should the types be discussed in?
-
The :mod:`!datetime` module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is
@@ -38,13 +36,14 @@ on efficient attribute extraction for output formatting and manipulation.
Third-party library with expanded time zone and parsing support.
Package :pypi:`DateType`
- Third-party library that introduces distinct static types to e.g. allow
- :term:`static type checkers `
+ Third-party library that introduces distinct static types to for example,
+ allow :term:`static type checkers `
to differentiate between naive and aware datetimes.
+
.. _datetime-naive-aware:
-Aware and Naive Objects
+Aware and naive objects
-----------------------
Date and time objects may be categorized as "aware" or "naive" depending on
@@ -77,6 +76,7 @@ detail is up to the application. The rules for time adjustment across the
world are more political than rational, change frequently, and there is no
standard suitable for every application aside from UTC.
+
Constants
---------
@@ -93,13 +93,15 @@ The :mod:`!datetime` module exports the following constants:
The largest year number allowed in a :class:`date` or :class:`.datetime` object.
:const:`MAXYEAR` is 9999.
+
.. data:: UTC
Alias for the UTC time zone singleton :attr:`datetime.timezone.utc`.
.. versionadded:: 3.11
-Available Types
+
+Available types
---------------
.. class:: date
@@ -142,6 +144,7 @@ Available Types
time adjustment (for example, to account for time zone and/or daylight saving
time).
+
.. class:: timezone
:noindex:
@@ -150,19 +153,19 @@ Available Types
.. versionadded:: 3.2
+
Objects of these types are immutable.
-Subclass relationships::
+Subclass relationships:
+
+.. figure:: datetime-inheritance.svg
+ :class: invert-in-dark-mode
+ :align: center
+ :alt: timedelta, tzinfo, time, and date inherit from object; timezone inherits
+ from tzinfo; and datetime inherits from date.
- object
- timedelta
- tzinfo
- timezone
- time
- date
- datetime
-Common Properties
+Common properties
^^^^^^^^^^^^^^^^^
The :class:`date`, :class:`.datetime`, :class:`.time`, and :class:`timezone` types
@@ -173,7 +176,8 @@ share these common features:
dictionary keys.
- Objects of these types support efficient pickling via the :mod:`pickle` module.
-Determining if an Object is Aware or Naive
+
+Determining if an object is aware or naive
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Objects of the :class:`date` type are always naive.
@@ -197,10 +201,11 @@ Otherwise, ``t`` is naive.
The distinction between aware and naive doesn't apply to :class:`timedelta`
objects.
+
.. _datetime-timedelta:
-:class:`timedelta` Objects
---------------------------
+:class:`!timedelta` objects
+---------------------------
A :class:`timedelta` object represents a duration, the difference between two
:class:`.datetime` or :class:`date` instances.
@@ -296,6 +301,7 @@ Class attributes:
The smallest possible difference between non-equal :class:`timedelta` objects,
``timedelta(microseconds=1)``.
+
Note that, because of normalization, ``timedelta.max`` is greater than ``-timedelta.min``.
``-timedelta.max`` is not representable as a :class:`timedelta` object.
@@ -326,6 +332,7 @@ Instance attributes (read-only):
>>> duration.total_seconds()
11235813.0
+
.. attribute:: timedelta.microseconds
Between 0 and 999,999 inclusive.
@@ -333,8 +340,6 @@ Instance attributes (read-only):
Supported operations:
-.. XXX this table is too wide!
-
+--------------------------------+-----------------------------------------------+
| Operation | Result |
+================================+===============================================+
@@ -396,7 +401,6 @@ Supported operations:
| | call with canonical attribute values. |
+--------------------------------+-----------------------------------------------+
-
Notes:
(1)
@@ -447,15 +451,16 @@ Instance methods:
Return the total number of seconds contained in the duration. Equivalent to
``td / timedelta(seconds=1)``. For interval units other than seconds, use the
- division form directly (e.g. ``td / timedelta(microseconds=1)``).
+ division form directly (for example, ``td / timedelta(microseconds=1)``).
Note that for very large time intervals (greater than 270 years on
most platforms) this method will lose microsecond accuracy.
.. versionadded:: 3.2
-Examples of usage: :class:`timedelta`
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Examples of usage: :class:`!timedelta`
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An additional example of normalization::
@@ -485,10 +490,11 @@ Examples of :class:`timedelta` arithmetic::
>>> three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
+
.. _datetime-date:
-:class:`date` Objects
----------------------
+:class:`!date` objects
+----------------------
A :class:`date` object represents a date (year, month and day) in an idealized
calendar, the current Gregorian calendar indefinitely extended in both
@@ -517,9 +523,10 @@ Other constructors, all class methods:
This is equivalent to ``date.fromtimestamp(time.time())``.
+
.. classmethod:: date.fromtimestamp(timestamp)
- Return the local date corresponding to the POSIX timestamp, such as is
+ Return the local date corresponding to the POSIX *timestamp*, such as is
returned by :func:`time.time`.
This may raise :exc:`OverflowError`, if the timestamp is out
@@ -541,7 +548,7 @@ Other constructors, all class methods:
.. classmethod:: date.fromordinal(ordinal)
- Return the date corresponding to the proleptic Gregorian ordinal, where
+ Return the date corresponding to the proleptic Gregorian *ordinal*, where
January 1 of year 1 has ordinal 1.
:exc:`ValueError` is raised unless ``1 <= ordinal <=
@@ -574,13 +581,15 @@ Other constructors, all class methods:
.. versionchanged:: 3.11
Previously, this method only supported the format ``YYYY-MM-DD``.
+
.. classmethod:: date.fromisocalendar(year, week, day)
Return a :class:`date` corresponding to the ISO calendar date specified by
- year, week and day. This is the inverse of the function :meth:`date.isocalendar`.
+ *year*, *week* and *day*. This is the inverse of the function :meth:`date.isocalendar`.
.. versionadded:: 3.8
+
.. classmethod:: date.strptime(date_string, format)
Return a :class:`.date` corresponding to *date_string*, parsed according to
@@ -791,6 +800,7 @@ Instance methods:
.. versionchanged:: 3.9
Result changed from a tuple to a :term:`named tuple`.
+
.. method:: date.isoformat()
Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``::
@@ -799,6 +809,7 @@ Instance methods:
>>> date(2002, 12, 4).isoformat()
'2002-12-04'
+
.. method:: date.__str__()
For a date ``d``, ``str(d)`` is equivalent to ``d.isoformat()``.
@@ -835,8 +846,9 @@ Instance methods:
literals ` and when using :meth:`str.format`.
See also :ref:`strftime-strptime-behavior` and :meth:`date.isoformat`.
-Examples of Usage: :class:`date`
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Examples of usage: :class:`!date`
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Example of counting days to an event::
@@ -878,7 +890,7 @@ More examples of working with :class:`date`:
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'
- >>> # Methods for to extracting 'components' under different calendars
+ >>> # Methods for extracting 'components' under different calendars
>>> t = d.timetuple()
>>> for i in t: # doctest: +SKIP
... print(i)
@@ -905,7 +917,7 @@ More examples of working with :class:`date`:
.. _datetime-datetime:
-:class:`.datetime` Objects
+:class:`!datetime` objects
--------------------------
A :class:`.datetime` object is a single object containing all the information
@@ -937,6 +949,7 @@ Constructor:
.. versionchanged:: 3.6
Added the *fold* parameter.
+
Other constructors, all class methods:
.. classmethod:: datetime.today()
@@ -952,6 +965,7 @@ Other constructors, all class methods:
This method is functionally equivalent to :meth:`now`, but without a
``tz`` parameter.
+
.. classmethod:: datetime.now(tz=None)
Return the current local date and time.
@@ -972,6 +986,7 @@ Other constructors, all class methods:
Subsequent calls to :meth:`!datetime.now` may return the same
instant depending on the precision of the underlying clock.
+
.. classmethod:: datetime.utcnow()
Return the current UTC date and time, with :attr:`.tzinfo` ``None``.
@@ -1063,13 +1078,13 @@ Other constructors, all class methods:
:c:func:`gmtime` function. Raise :exc:`OSError` instead of
:exc:`ValueError` on :c:func:`gmtime` failure.
+ .. versionchanged:: 3.15
+ Accepts any real number as *timestamp*, not only integer or float.
+
.. deprecated:: 3.12
Use :meth:`datetime.fromtimestamp` with :const:`UTC` instead.
- .. versionchanged:: 3.15
- Accepts any real number as *timestamp*, not only integer or float.
-
.. classmethod:: datetime.fromordinal(ordinal)
@@ -1142,12 +1157,13 @@ Other constructors, all class methods:
.. classmethod:: datetime.fromisocalendar(year, week, day)
Return a :class:`.datetime` corresponding to the ISO calendar date specified
- by year, week and day. The non-date components of the datetime are populated
+ by *year*, *week* and *day*. The non-date components of the datetime are populated
with their normal default values. This is the inverse of the function
:meth:`datetime.isocalendar`.
.. versionadded:: 3.8
+
.. classmethod:: datetime.strptime(date_string, format)
Return a :class:`.datetime` corresponding to *date_string*, parsed according to
@@ -1255,6 +1271,7 @@ Instance attributes (read-only):
.. versionadded:: 3.6
+
Supported operations:
+---------------------------------------+--------------------------------+
@@ -1345,6 +1362,7 @@ Supported operations:
The default behavior can be changed by overriding the special comparison
methods in subclasses.
+
Instance methods:
.. method:: datetime.date()
@@ -1500,11 +1518,13 @@ Instance methods:
``datetime.replace(tzinfo=timezone.utc)`` to make it aware, at which point
you can use :meth:`.datetime.timetuple`.
+
.. method:: datetime.toordinal()
Return the proleptic Gregorian ordinal of the date. The same as
``self.date().toordinal()``.
+
.. method:: datetime.timestamp()
Return POSIX timestamp corresponding to the :class:`.datetime`
@@ -1523,16 +1543,6 @@ Instance methods:
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
- .. versionadded:: 3.3
-
- .. versionchanged:: 3.6
- The :meth:`timestamp` method uses the :attr:`.fold` attribute to
- disambiguate the times during a repeated interval.
-
- .. versionchanged:: 3.6
- This method no longer relies on the platform C :c:func:`mktime`
- function to perform conversions.
-
.. note::
There is no method to obtain the POSIX timestamp directly from a
@@ -1547,6 +1557,17 @@ Instance methods:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
+ .. versionadded:: 3.3
+
+ .. versionchanged:: 3.6
+ The :meth:`timestamp` method uses the :attr:`.fold` attribute to
+ disambiguate the times during a repeated interval.
+
+ .. versionchanged:: 3.6
+ This method no longer relies on the platform C :c:func:`mktime`
+ function to perform conversions.
+
+
.. method:: datetime.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
@@ -1675,7 +1696,7 @@ Instance methods:
See also :ref:`strftime-strptime-behavior` and :meth:`datetime.isoformat`.
-Examples of Usage: :class:`.datetime`
+Examples of usage: :class:`!datetime`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Examples of working with :class:`.datetime` objects:
@@ -1801,9 +1822,10 @@ Usage of ``KabulTz`` from above::
>>> dt2 == dt3
True
+
.. _datetime-time:
-:class:`.time` Objects
+:class:`!time` objects
----------------------
A :class:`.time` object represents a (local) time of day, independent of any particular
@@ -1824,6 +1846,7 @@ day, and subject to adjustment via a :class:`tzinfo` object.
If an argument outside those ranges is given, :exc:`ValueError` is raised. All
default to 0 except *tzinfo*, which defaults to ``None``.
+
Class attributes:
@@ -1882,6 +1905,7 @@ Instance attributes (read-only):
.. versionadded:: 3.6
+
:class:`.time` objects support equality and order comparisons,
where ``a`` is considered less than ``b`` when ``a`` precedes ``b`` in time.
@@ -1904,8 +1928,8 @@ In Boolean contexts, a :class:`.time` object is always considered to be true.
.. versionchanged:: 3.5
Before Python 3.5, a :class:`.time` object was considered to be false if it
represented midnight in UTC. This behavior was considered obscure and
- error-prone and has been removed in Python 3.5. See :issue:`13936` for full
- details.
+ error-prone and has been removed in Python 3.5. See :issue:`13936` for more
+ information.
Other constructors:
@@ -1950,6 +1974,7 @@ Other constructors:
Previously, this method only supported formats that could be emitted by
:meth:`time.isoformat`.
+
.. classmethod:: time.strptime(date_string, format)
Return a :class:`.time` corresponding to *date_string*, parsed according to
@@ -2066,13 +2091,15 @@ Instance methods:
.. versionchanged:: 3.7
The DST offset is not restricted to a whole number of minutes.
+
.. method:: time.tzname()
If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
return ``None`` or a string object.
-Examples of Usage: :class:`.time`
+
+Examples of usage: :class:`!time`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Examples of working with a :class:`.time` object::
@@ -2105,12 +2132,12 @@ Examples of working with a :class:`.time` object::
.. _datetime-tzinfo:
-:class:`tzinfo` Objects
------------------------
+:class:`!tzinfo` objects
+------------------------
.. class:: tzinfo()
- This is an abstract base class, meaning that this class should not be
+ This is an :term:`abstract base class`, meaning that this class should not be
instantiated directly. Define a subclass of :class:`tzinfo` to capture
information about a particular time zone.
@@ -2381,8 +2408,8 @@ only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
.. _datetime-timezone:
-:class:`timezone` Objects
--------------------------
+:class:`!timezone` objects
+--------------------------
The :class:`timezone` class is a subclass of :class:`tzinfo`, each
instance of which represents a time zone defined by a fixed offset from
@@ -2420,6 +2447,7 @@ where historical changes have been made to civil time.
.. versionchanged:: 3.7
The UTC offset is not restricted to a whole number of minutes.
+
.. method:: timezone.tzname(dt)
Return the fixed value specified when the :class:`timezone` instance
@@ -2440,11 +2468,13 @@ where historical changes have been made to civil time.
Always returns ``None``.
+
.. method:: timezone.fromutc(dt)
Return ``dt + offset``. The *dt* argument must be an aware
:class:`.datetime` instance, with ``tzinfo`` set to ``self``.
+
Class attributes:
.. attribute:: timezone.utc
@@ -2457,8 +2487,8 @@ Class attributes:
.. _strftime-strptime-behavior:
-:meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Behavior
---------------------------------------------------------------------
+:meth:`!strftime` and :meth:`!strptime` behavior
+------------------------------------------------
:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
``strftime(format)`` method, to create a string representing the time under the
@@ -2484,8 +2514,8 @@ versus :meth:`~.datetime.strptime`:
.. _format-codes:
-:meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Format Codes
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+:meth:`!strftime` and :meth:`!strptime` format codes
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
These methods accept format codes that can be used to parse and format dates::
@@ -2678,7 +2708,8 @@ differences between platforms in handling of unsupported format specifiers.
.. versionadded:: 3.15
``%:z`` was added for :meth:`~.datetime.strptime`
-Technical Detail
+
+Technical detail
^^^^^^^^^^^^^^^^
Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
@@ -2695,7 +2726,6 @@ in the format string will be pulled from the default value.
the default year of 1900 is *not* a leap year. Always add a default leap
year to partial date strings before parsing.
-
.. testsetup::
# doctest seems to turn the warning into an error which makes it