--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<!-- Generated by graphviz version 12.2.1 (20241206.2353)
+ -->
+<!-- Title: datetime class hierarchy Pages: 1 -->
+<svg width="386pt" height="188pt"
+ viewBox="0.00 0.00 385.60 188.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 184)">
+<title>datetime class hierarchy</title>
+<!-- object -->
+<g id="node1" class="node">
+<title>object</title>
+<path fill="none" stroke="black" d="M216.85,-180C216.85,-180 178.75,-180 178.75,-180 172.75,-180 166.75,-174 166.75,-168 166.75,-168 166.75,-156 166.75,-156 166.75,-150 172.75,-144 178.75,-144 178.75,-144 216.85,-144 216.85,-144 222.85,-144 228.85,-150 228.85,-156 228.85,-156 228.85,-168 228.85,-168 228.85,-174 222.85,-180 216.85,-180"/>
+<text text-anchor="middle" x="197.8" y="-156.57" font-family="monospace,monospace" font-size="14.00">object</text>
+</g>
+<!-- tzinfo -->
+<g id="node2" class="node">
+<title>tzinfo</title>
+<path fill="none" stroke="black" d="M56.85,-108C56.85,-108 18.75,-108 18.75,-108 12.75,-108 6.75,-102 6.75,-96 6.75,-96 6.75,-84 6.75,-84 6.75,-78 12.75,-72 18.75,-72 18.75,-72 56.85,-72 56.85,-72 62.85,-72 68.85,-78 68.85,-84 68.85,-84 68.85,-96 68.85,-96 68.85,-102 62.85,-108 56.85,-108"/>
+<text text-anchor="middle" x="37.8" y="-84.58" font-family="monospace,monospace" font-size="14.00">tzinfo</text>
+</g>
+<!-- object->tzinfo -->
+<g id="edge1" class="edge">
+<title>object->tzinfo</title>
+<path fill="none" stroke="black" d="M166.57,-147.34C138.47,-135.04 97.38,-117.07 69.22,-104.75"/>
+</g>
+<!-- timedelta -->
+<g id="node3" class="node">
+<title>timedelta</title>
+<path fill="none" stroke="black" d="M174.98,-108C174.98,-108 116.63,-108 116.63,-108 110.63,-108 104.63,-102 104.63,-96 104.63,-96 104.63,-84 104.63,-84 104.63,-78 110.63,-72 116.63,-72 116.63,-72 174.98,-72 174.98,-72 180.98,-72 186.98,-78 186.98,-84 186.98,-84 186.98,-96 186.98,-96 186.98,-102 180.98,-108 174.98,-108"/>
+<text text-anchor="middle" x="145.8" y="-84.58" font-family="monospace,monospace" font-size="14.00">timedelta</text>
+</g>
+<!-- object->timedelta -->
+<g id="edge2" class="edge">
+<title>object->timedelta</title>
+<path fill="none" stroke="black" d="M184.95,-143.7C176.89,-132.85 166.54,-118.92 158.51,-108.1"/>
+</g>
+<!-- time -->
+<g id="node4" class="node">
+<title>time</title>
+<path fill="none" stroke="black" d="M264.8,-108C264.8,-108 234.8,-108 234.8,-108 228.8,-108 222.8,-102 222.8,-96 222.8,-96 222.8,-84 222.8,-84 222.8,-78 228.8,-72 234.8,-72 234.8,-72 264.8,-72 264.8,-72 270.8,-72 276.8,-78 276.8,-84 276.8,-84 276.8,-96 276.8,-96 276.8,-102 270.8,-108 264.8,-108"/>
+<text text-anchor="middle" x="249.8" y="-84.58" font-family="monospace,monospace" font-size="14.00">time</text>
+</g>
+<!-- object->time -->
+<g id="edge3" class="edge">
+<title>object->time</title>
+<path fill="none" stroke="black" d="M210.65,-143.7C218.71,-132.85 229.06,-118.92 237.09,-108.1"/>
+</g>
+<!-- date -->
+<g id="node5" class="node">
+<title>date</title>
+<path fill="none" stroke="black" d="M354.8,-108C354.8,-108 324.8,-108 324.8,-108 318.8,-108 312.8,-102 312.8,-96 312.8,-96 312.8,-84 312.8,-84 312.8,-78 318.8,-72 324.8,-72 324.8,-72 354.8,-72 354.8,-72 360.8,-72 366.8,-78 366.8,-84 366.8,-84 366.8,-96 366.8,-96 366.8,-102 360.8,-108 354.8,-108"/>
+<text text-anchor="middle" x="339.8" y="-84.58" font-family="monospace,monospace" font-size="14.00">date</text>
+</g>
+<!-- object->date -->
+<g id="edge4" class="edge">
+<title>object->date</title>
+<path fill="none" stroke="black" d="M229.31,-145.46C254.32,-133.14 288.9,-116.09 312.68,-104.37"/>
+</g>
+<!-- timezone -->
+<g id="node6" class="node">
+<title>timezone</title>
+<path fill="none" stroke="black" d="M63.6,-36C63.6,-36 12,-36 12,-36 6,-36 0,-30 0,-24 0,-24 0,-12 0,-12 0,-6 6,0 12,0 12,0 63.6,0 63.6,0 69.6,0 75.6,-6 75.6,-12 75.6,-12 75.6,-24 75.6,-24 75.6,-30 69.6,-36 63.6,-36"/>
+<text text-anchor="middle" x="37.8" y="-12.57" font-family="monospace,monospace" font-size="14.00">timezone</text>
+</g>
+<!-- tzinfo->timezone -->
+<g id="edge5" class="edge">
+<title>tzinfo->timezone</title>
+<path fill="none" stroke="black" d="M37.8,-71.7C37.8,-60.85 37.8,-46.92 37.8,-36.1"/>
+</g>
+<!-- datetime -->
+<g id="node7" class="node">
+<title>datetime</title>
+<path fill="none" stroke="black" d="M365.6,-36C365.6,-36 314,-36 314,-36 308,-36 302,-30 302,-24 302,-24 302,-12 302,-12 302,-6 308,0 314,0 314,0 365.6,0 365.6,0 371.6,0 377.6,-6 377.6,-12 377.6,-12 377.6,-24 377.6,-24 377.6,-30 371.6,-36 365.6,-36"/>
+<text text-anchor="middle" x="339.8" y="-12.57" font-family="monospace,monospace" font-size="14.00">datetime</text>
+</g>
+<!-- date->datetime -->
+<g id="edge6" class="edge">
+<title>date->datetime</title>
+<path fill="none" stroke="black" d="M339.8,-71.7C339.8,-60.85 339.8,-46.92 339.8,-36.1"/>
+</g>
+</g>
+</svg>
--------------
-.. 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
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 <static type checker>`
+ Third-party library that introduces distinct static types to for example,
+ allow :term:`static type checkers <static type checker>`
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
world are more political than rational, change frequently, and there is no
standard suitable for every application aside from UTC.
+
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
time adjustment (for example, to account for time zone and/or daylight saving
time).
+
.. class:: timezone
:noindex:
.. 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
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.
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.
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.
>>> duration.total_seconds()
11235813.0
+
.. attribute:: timedelta.microseconds
Between 0 and 999,999 inclusive.
Supported operations:
-.. XXX this table is too wide!
-
+--------------------------------+-----------------------------------------------+
| Operation | Result |
+================================+===============================================+
| | call with canonical attribute values. |
+--------------------------------+-----------------------------------------------+
-
Notes:
(1)
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::
>>> 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
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
.. 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 <=
.. 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
.. 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``::
>>> date(2002, 12, 4).isoformat()
'2002-12-04'
+
.. method:: date.__str__()
For a date ``d``, ``str(d)`` is equivalent to ``d.isoformat()``.
literals <f-strings>` 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::
>>> '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)
.. _datetime-datetime:
-:class:`.datetime` Objects
+:class:`!datetime` objects
--------------------------
A :class:`.datetime` object is a single object containing all the information
.. versionchanged:: 3.6
Added the *fold* parameter.
+
Other constructors, all class methods:
.. classmethod:: datetime.today()
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.
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``.
: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)
.. 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
.. versionadded:: 3.6
+
Supported operations:
+---------------------------------------+--------------------------------+
The default behavior can be changed by overriding the special comparison
methods in subclasses.
+
Instance methods:
.. method:: datetime.date()
``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`
(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
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.
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:
>>> 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
If an argument outside those ranges is given, :exc:`ValueError` is raised. All
default to 0 except *tzinfo*, which defaults to ``None``.
+
Class attributes:
.. versionadded:: 3.6
+
:class:`.time` objects support equality and order comparisons,
where ``a`` is considered less than ``b`` when ``a`` precedes ``b`` in time.
.. 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:
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
.. 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::
.. _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.
.. _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
.. 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
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
.. _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
.. _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::
.. versionadded:: 3.15
``%:z``, ``%F``, and ``%D`` were added for :meth:`~.datetime.strptime`.
-Technical Detail
+
+Technical detail
^^^^^^^^^^^^^^^^
Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
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