]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Docs: replace all `datetime` imports with `import datetime as dt` (#145640)
authorHugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Sat, 21 Mar 2026 16:02:06 +0000 (18:02 +0200)
committerGitHub <noreply@github.com>
Sat, 21 Mar 2026 16:02:06 +0000 (18:02 +0200)
26 files changed:
Doc/faq/programming.rst
Doc/howto/enum.rst
Doc/howto/logging-cookbook.rst
Doc/includes/diff.py
Doc/library/asyncio-eventloop.rst
Doc/library/asyncio-protocol.rst
Doc/library/asyncio-subprocess.rst
Doc/library/asyncio-task.rst
Doc/library/difflib.rst
Doc/library/enum.rst
Doc/library/plistlib.rst
Doc/library/sqlite3.rst
Doc/library/ssl.rst
Doc/library/string.rst
Doc/library/unittest.mock-examples.rst
Doc/library/xmlrpc.client.rst
Doc/library/xmlrpc.server.rst
Doc/library/zoneinfo.rst
Doc/tutorial/stdlib.rst
Doc/whatsnew/2.3.rst
Doc/whatsnew/2.5.rst
Doc/whatsnew/2.6.rst
Doc/whatsnew/3.2.rst
Doc/whatsnew/3.8.rst
Doc/whatsnew/3.9.rst
Lib/plistlib.py

index 8bd2bc99d74b838519c0de4704b2f25575ddd198..ff34bb5d71c22baceb14757dbeb5e94cee1844b1 100644 (file)
@@ -1074,7 +1074,7 @@ Performance
 My program is too slow. How do I speed it up?
 ---------------------------------------------
 
-That's a tough one, in general.  First, here is list of things to
+That's a tough one, in general.  First, here is list of things to
 remember before diving further:
 
 * Performance characteristics vary across Python implementations.  This FAQ
index 93850b57af2c65e7359d98288418ff90e6f1277b..5260c2ca4add4717524ab583465f75954c9f49bc 100644 (file)
@@ -105,8 +105,8 @@ The complete :class:`!Weekday` enum now looks like this::
 
 Now we can find out what today is!  Observe::
 
-    >>> from datetime import date
-    >>> Weekday.from_date(date.today())     # doctest: +SKIP
+    >>> import datetime as dt
+    >>> Weekday.from_date(dt.date.today())     # doctest: +SKIP
     <Weekday.TUESDAY: 2>
 
 Of course, if you're reading this on some other day, you'll see that day instead.
@@ -1480,8 +1480,8 @@ TimePeriod
 
 An example to show the :attr:`~Enum._ignore_` attribute in use::
 
-    >>> from datetime import timedelta
-    >>> class Period(timedelta, Enum):
+    >>> import datetime as dt
+    >>> class Period(dt.timedelta, Enum):
     ...     "different lengths of time"
     ...     _ignore_ = 'Period i'
     ...     Period = vars()
index b87ac93296b9151497196896d90cf3ef0c4dcc20..21df6ba858d8c2ddc722ed1fefbcdfc3313f5539 100644 (file)
@@ -1549,10 +1549,10 @@ to this (remembering to first import :mod:`concurrent.futures`)::
         for i in range(10):
             executor.submit(worker_process, queue, worker_configurer)
 
-Deploying Web applications using Gunicorn and uWSGI
+Deploying web applications using Gunicorn and uWSGI
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-When deploying Web applications using `Gunicorn <https://gunicorn.org/>`_ or `uWSGI
+When deploying web applications using `Gunicorn <https://gunicorn.org/>`_ or `uWSGI
 <https://uwsgi-docs.readthedocs.io/en/latest/>`_ (or similar), multiple worker
 processes are created to handle client requests. In such environments, avoid creating
 file-based handlers directly in your web application. Instead, use a
@@ -3616,7 +3616,6 @@ detailed information.
 
 .. code-block:: python3
 
-    import datetime
     import logging
     import random
     import sys
@@ -3851,7 +3850,7 @@ Logging to syslog with RFC5424 support
 Although :rfc:`5424` dates from 2009, most syslog servers are configured by default to
 use the older :rfc:`3164`, which hails from 2001. When ``logging`` was added to Python
 in 2003, it supported the earlier (and only existing) protocol at the time. Since
-RFC5424 came out, as there has not been widespread deployment of it in syslog
+RFC 5424 came out, as there has not been widespread deployment of it in syslog
 servers, the :class:`~logging.handlers.SysLogHandler` functionality has not been
 updated.
 
@@ -3859,7 +3858,7 @@ RFC 5424 contains some useful features such as support for structured data, and
 need to be able to log to a syslog server with support for it, you can do so with a
 subclassed handler which looks something like this::
 
-    import datetime
+    import datetime as dt
     import logging.handlers
     import re
     import socket
@@ -3877,7 +3876,7 @@ subclassed handler which looks something like this::
 
         def format(self, record):
             version = 1
-            asctime = datetime.datetime.fromtimestamp(record.created).isoformat()
+            asctime = dt.datetime.fromtimestamp(record.created).isoformat()
             m = self.tz_offset.match(time.strftime('%z'))
             has_offset = False
             if m and time.timezone:
index 001619f5f83fc084cb9c43bd60a588f83ce6c647..bc4bd58ff3e3f1154615623958cc991b2672cc6c 100644 (file)
@@ -1,4 +1,4 @@
-""" Command line interface to difflib.py providing diffs in four formats:
+""" Command-line interface to difflib.py providing diffs in four formats:
 
 * ndiff:    lists every line and highlights interline changes.
 * context:  highlights clusters of changes in a before/after format.
@@ -8,11 +8,11 @@
 """
 
 import sys, os, difflib, argparse
-from datetime import datetime, timezone
+import datetime as dt
 
 def file_mtime(path):
-    t = datetime.fromtimestamp(os.stat(path).st_mtime,
-                               timezone.utc)
+    t = dt.datetime.fromtimestamp(os.stat(path).st_mtime,
+                                  dt.timezone.utc)
     return t.astimezone().isoformat()
 
 def main():
index bdb24b3a58c267c2175e9a8ec3d5d8afddd9d0d4..d1a5b4e7b4638eb20c5ea8e7be15fa6a56aec8b5 100644 (file)
@@ -4,7 +4,7 @@
 .. _asyncio-event-loop:
 
 ==========
-Event Loop
+Event loop
 ==========
 
 **Source code:** :source:`Lib/asyncio/events.py`,
@@ -105,7 +105,7 @@ This documentation page contains the following sections:
 
 .. _asyncio-event-loop-methods:
 
-Event Loop Methods
+Event loop methods
 ==================
 
 Event loops have **low-level** APIs for the following:
@@ -361,7 +361,7 @@ clocks to track time.
    The :func:`asyncio.sleep` function.
 
 
-Creating Futures and Tasks
+Creating futures and tasks
 ^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. method:: loop.create_future()
@@ -962,7 +962,7 @@ Transferring files
    .. versionadded:: 3.7
 
 
-TLS Upgrade
+TLS upgrade
 ^^^^^^^^^^^
 
 .. method:: loop.start_tls(transport, protocol, \
@@ -1431,7 +1431,7 @@ Executing code in thread or process pools
       :class:`~concurrent.futures.ThreadPoolExecutor`.
 
 
-Error Handling API
+Error handling API
 ^^^^^^^^^^^^^^^^^^
 
 Allows customizing how exceptions are handled in the event loop.
@@ -1534,7 +1534,7 @@ Enabling debug mode
    The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
 
 
-Running Subprocesses
+Running subprocesses
 ^^^^^^^^^^^^^^^^^^^^
 
 Methods described in this subsections are low-level.  In regular
@@ -1672,7 +1672,7 @@ async/await code consider using the high-level
    are going to be used to construct shell commands.
 
 
-Callback Handles
+Callback handles
 ================
 
 .. class:: Handle
@@ -1715,7 +1715,7 @@ Callback Handles
       .. versionadded:: 3.7
 
 
-Server Objects
+Server objects
 ==============
 
 Server objects are created by :meth:`loop.create_server`,
@@ -1858,7 +1858,7 @@ Do not instantiate the :class:`Server` class directly.
 .. _asyncio-event-loops:
 .. _asyncio-event-loop-implementations:
 
-Event Loop Implementations
+Event loop implementations
 ==========================
 
 asyncio ships with two different event loop implementations:
@@ -1971,10 +1971,10 @@ callback uses the :meth:`loop.call_later` method to reschedule itself
 after 5 seconds, and then stops the event loop::
 
     import asyncio
-    import datetime
+    import datetime as dt
 
     def display_date(end_time, loop):
-        print(datetime.datetime.now())
+        print(dt.datetime.now())
         if (loop.time() + 1.0) < end_time:
             loop.call_later(1, display_date, end_time, loop)
         else:
index 5208f14c94a50f0526f7872cb36868f47da0ce50..58f77feb31198410c6fa95cb7219927414172556 100644 (file)
@@ -1037,7 +1037,7 @@ The subprocess is created by the :meth:`loop.subprocess_exec` method::
         # low-level APIs.
         loop = asyncio.get_running_loop()
 
-        code = 'import datetime; print(datetime.datetime.now())'
+        code = 'import datetime as dt; print(dt.datetime.now())'
         exit_future = asyncio.Future(loop=loop)
 
         # Create the subprocess controlled by DateProtocol;
index cb9ddc08a64d9b37561f61541b32d828655b950a..a6514649bf9a0a82b7b9730452dc1a75afd05b35 100644 (file)
@@ -359,7 +359,7 @@ function::
     import sys
 
     async def get_date():
-        code = 'import datetime; print(datetime.datetime.now())'
+        code = 'import datetime as dt; print(dt.datetime.now())'
 
         # Create the subprocess; redirect the standard output
         # into a pipe.
index e2a6752be12b670dfbd8d8b97a6b8fc272a24c92..4e60eee44290afc558f93ad4a75d3b4c3499fc03 100644 (file)
@@ -2,7 +2,7 @@
 
 
 ====================
-Coroutines and Tasks
+Coroutines and tasks
 ====================
 
 This section outlines high-level asyncio APIs to work with coroutines
@@ -231,7 +231,7 @@ A good example of a low-level function that returns a Future object
 is :meth:`loop.run_in_executor`.
 
 
-Creating Tasks
+Creating tasks
 ==============
 
 **Source code:** :source:`Lib/asyncio/tasks.py`
@@ -300,7 +300,7 @@ Creating Tasks
       Added the *eager_start* parameter by passing on all *kwargs*.
 
 
-Task Cancellation
+Task cancellation
 =================
 
 Tasks can easily and safely be cancelled.
@@ -324,7 +324,7 @@ remove the cancellation state.
 
 .. _taskgroups:
 
-Task Groups
+Task groups
 ===========
 
 Task groups combine a task creation API with a convenient
@@ -427,7 +427,7 @@ reported by :meth:`asyncio.Task.cancelling`.
    Improved handling of simultaneous internal and external cancellations
    and correct preservation of cancellation counts.
 
-Terminating a Task Group
+Terminating a task group
 ------------------------
 
 While terminating a task group is not natively supported by the standard
@@ -498,13 +498,13 @@ Sleeping
    for 5 seconds::
 
     import asyncio
-    import datetime
+    import datetime as dt
 
     async def display_date():
         loop = asyncio.get_running_loop()
         end_time = loop.time() + 5.0
         while True:
-            print(datetime.datetime.now())
+            print(dt.datetime.now())
             if (loop.time() + 1.0) >= end_time:
                 break
             await asyncio.sleep(1)
@@ -519,7 +519,7 @@ Sleeping
       Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
 
 
-Running Tasks Concurrently
+Running tasks concurrently
 ==========================
 
 .. awaitablefunction:: gather(*aws, return_exceptions=False)
@@ -621,7 +621,7 @@ Running Tasks Concurrently
 
 .. _eager-task-factory:
 
-Eager Task Factory
+Eager task factory
 ==================
 
 .. function:: eager_task_factory(loop, coro, *, name=None, context=None)
@@ -664,7 +664,7 @@ Eager Task Factory
     .. versionadded:: 3.12
 
 
-Shielding From Cancellation
+Shielding from cancellation
 ===========================
 
 .. awaitablefunction:: shield(aw)
@@ -894,7 +894,7 @@ Timeouts
       Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`.
 
 
-Waiting Primitives
+Waiting primitives
 ==================
 
 .. function:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
@@ -1014,7 +1014,7 @@ Waiting Primitives
       or as a plain :term:`iterator` (previously it was only a plain iterator).
 
 
-Running in Threads
+Running in threads
 ==================
 
 .. function:: to_thread(func, /, *args, **kwargs)
@@ -1074,7 +1074,7 @@ Running in Threads
    .. versionadded:: 3.9
 
 
-Scheduling From Other Threads
+Scheduling from other threads
 =============================
 
 .. function:: run_coroutine_threadsafe(coro, loop)
@@ -1198,7 +1198,7 @@ Introspection
 
 .. _asyncio-task-obj:
 
-Task Object
+Task object
 ===========
 
 .. class:: Task(coro, *, loop=None, name=None, context=None, eager_start=False)
index e56c4f5e7dfbf7fbbb5c67d72891d0a28a1f049f..8b812c173b595368a8d87392fb90c003958247c8 100644 (file)
@@ -362,7 +362,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
 
 .. _sequence-matcher:
 
-SequenceMatcher Objects
+SequenceMatcher objects
 -----------------------
 
 The :class:`SequenceMatcher` class has this constructor:
@@ -590,7 +590,7 @@ are always at least as large as :meth:`~SequenceMatcher.ratio`:
 
 .. _sequencematcher-examples:
 
-SequenceMatcher Examples
+SequenceMatcher examples
 ------------------------
 
 This example compares two strings, considering blanks to be "junk":
@@ -641,7 +641,7 @@ If you want to know how to change the first sequence into the second, use
 
 .. _differ-objects:
 
-Differ Objects
+Differ objects
 --------------
 
 Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
@@ -690,7 +690,7 @@ The :class:`Differ` class has this constructor:
 
 .. _differ-examples:
 
-Differ Example
+Differ example
 --------------
 
 This example compares two texts. First we set up the texts, sequences of
index 8a8a2edc9e542d1f3f22e1d0f0512f9d5b5271c3..0a1d2a0bac33abc94e1e160b2bd777c8814f52ef 100644 (file)
@@ -56,7 +56,7 @@ are not normal Python classes.  See
 
 ---------------
 
-Module Contents
+Module contents
 ---------------
 
    :class:`EnumType`
@@ -161,7 +161,7 @@ Module Contents
 
 ---------------
 
-Data Types
+Data types
 ----------
 
 
@@ -341,7 +341,7 @@ Data Types
       any public methods defined on *self.__class__*::
 
          >>> from enum import Enum
-         >>> from datetime import date
+         >>> import datetime as dt
          >>> class Weekday(Enum):
          ...     MONDAY = 1
          ...     TUESDAY = 2
@@ -352,7 +352,7 @@ Data Types
          ...     SUNDAY = 7
          ...     @classmethod
          ...     def today(cls):
-         ...         print('today is %s' % cls(date.today().isoweekday()).name)
+         ...         print(f'today is {cls(dt.date.today().isoweekday()).name}')
          ...
          >>> dir(Weekday.SATURDAY)
          ['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
@@ -970,7 +970,7 @@ Supported ``_sunder_`` names
 
 ---------------
 
-Utilities and Decorators
+Utilities and decorators
 ------------------------
 
 .. class:: auto
index e5fc19f495226e550b9f4aef495d44325f53ee6f..fa15cd4267eef4928da56dd0bdab14dd4170ab72 100644 (file)
@@ -180,7 +180,7 @@ Examples
 
 Generating a plist::
 
-    import datetime
+    import datetime as dt
     import plistlib
 
     pl = dict(
@@ -196,7 +196,7 @@ Generating a plist::
         ),
         someData = b"<binary gunk>",
         someMoreData = b"<lots of binary gunk>" * 10,
-        aDate = datetime.datetime.now()
+        aDate = dt.datetime.now()
     )
     print(plistlib.dumps(pl).decode())
 
index 40d103c13f8f3834fe11958328a2f6114b53638e..ff1676c5bfb56198b6d53f89d8af03420ab68219 100644 (file)
@@ -2285,7 +2285,7 @@ This section shows recipes for common adapters and converters.
 
 .. testcode::
 
-   import datetime
+   import datetime as dt
    import sqlite3
 
    def adapt_date_iso(val):
@@ -2300,21 +2300,21 @@ This section shows recipes for common adapters and converters.
        """Adapt datetime.datetime to Unix timestamp."""
        return int(val.timestamp())
 
-   sqlite3.register_adapter(datetime.date, adapt_date_iso)
-   sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
-   sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)
+   sqlite3.register_adapter(dt.date, adapt_date_iso)
+   sqlite3.register_adapter(dt.datetime, adapt_datetime_iso)
+   sqlite3.register_adapter(dt.datetime, adapt_datetime_epoch)
 
    def convert_date(val):
        """Convert ISO 8601 date to datetime.date object."""
-       return datetime.date.fromisoformat(val.decode())
+       return dt.date.fromisoformat(val.decode())
 
    def convert_datetime(val):
        """Convert ISO 8601 datetime to datetime.datetime object."""
-       return datetime.datetime.fromisoformat(val.decode())
+       return dt.datetime.fromisoformat(val.decode())
 
    def convert_timestamp(val):
        """Convert Unix epoch timestamp to datetime.datetime object."""
-       return datetime.datetime.fromtimestamp(int(val))
+       return dt.datetime.fromtimestamp(int(val))
 
    sqlite3.register_converter("date", convert_date)
    sqlite3.register_converter("datetime", convert_datetime)
@@ -2323,17 +2323,17 @@ This section shows recipes for common adapters and converters.
 .. testcode::
    :hide:
 
-   dt = datetime.datetime(2019, 5, 18, 15, 17, 8, 123456)
+   when = dt.datetime(2019, 5, 18, 15, 17, 8, 123456)
 
-   assert adapt_date_iso(dt.date()) == "2019-05-18"
-   assert convert_date(b"2019-05-18") == dt.date()
+   assert adapt_date_iso(when.date()) == "2019-05-18"
+   assert convert_date(b"2019-05-18") == when.date()
 
-   assert adapt_datetime_iso(dt) == "2019-05-18T15:17:08.123456"
-   assert convert_datetime(b"2019-05-18T15:17:08.123456") == dt
+   assert adapt_datetime_iso(when) == "2019-05-18T15:17:08.123456"
+   assert convert_datetime(b"2019-05-18T15:17:08.123456") == when
 
    # Using current time as fromtimestamp() returns local date/time.
    # Dropping microseconds as adapt_datetime_epoch truncates fractional second part.
-   now = datetime.datetime.now().replace(microsecond=0)
+   now = dt.datetime.now().replace(microsecond=0)
    current_timestamp = int(now.timestamp())
 
    assert adapt_datetime_epoch(now) == current_timestamp
index e83c2c9a8bc792c7151a5beb4701d487ffc0332d..f2c35d1897a77f8d8114b40554949f5401922aec 100644 (file)
@@ -67,7 +67,7 @@ by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
    Use of deprecated constants and functions result in deprecation warnings.
 
 
-Functions, Constants, and Exceptions
+Functions, constants, and exceptions
 ------------------------------------
 
 
@@ -374,7 +374,7 @@ Certificate handling
 
 .. function:: cert_time_to_seconds(cert_time)
 
-   Return the time in seconds since the Epoch, given the ``cert_time``
+   Return the time in seconds since the epoch, given the ``cert_time``
    string representing the "notBefore" or "notAfter" date from a
    certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C
    locale).
@@ -384,12 +384,12 @@ Certificate handling
    .. doctest:: newcontext
 
       >>> import ssl
+      >>> import datetime as dt
       >>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
       >>> timestamp  # doctest: +SKIP
       1515144883
-      >>> from datetime import datetime
-      >>> print(datetime.utcfromtimestamp(timestamp))  # doctest: +SKIP
-      2018-01-05 09:34:43
+      >>> print(dt.datetime.fromtimestamp(timestamp, dt.UTC))  # doctest: +SKIP
+      2018-01-05 09:34:43+00:00
 
    "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`).
 
@@ -1072,7 +1072,7 @@ Constants
       :attr:`TLSVersion.TLSv1_3` are deprecated.
 
 
-SSL Sockets
+SSL sockets
 -----------
 
 .. class:: SSLSocket(socket.socket)
@@ -1462,7 +1462,7 @@ SSL sockets also have the following additional methods and attributes:
    .. versionadded:: 3.6
 
 
-SSL Contexts
+SSL contexts
 ------------
 
 .. versionadded:: 3.2
@@ -2653,7 +2653,7 @@ thus several things you need to be aware of:
    as well.
 
 
-Memory BIO Support
+Memory BIO support
 ------------------
 
 .. versionadded:: 3.5
index 8096d90317d93f05c172f2fdf939dff3b3cb1304..08ccdfa3f454f8d61e4cb41ea0e8894c94dec0c0 100644 (file)
@@ -82,7 +82,7 @@ The constants defined in this module are:
 
 .. _string-formatting:
 
-Custom String Formatting
+Custom string formatting
 ------------------------
 
 The built-in string class provides the ability to do complex variable
@@ -192,7 +192,7 @@ implementation as the built-in :meth:`~str.format` method.
 
 .. _formatstrings:
 
-Format String Syntax
+Format string syntax
 --------------------
 
 The :meth:`str.format` method and the :class:`Formatter` class share the same
@@ -304,7 +304,7 @@ See the :ref:`formatexamples` section for some examples.
 
 .. _formatspec:
 
-Format Specification Mini-Language
+Format specification mini-language
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 "Format specifications" are used within replacement fields contained within a
@@ -759,8 +759,8 @@ Expressing a percentage::
 
 Using type-specific formatting::
 
-   >>> import datetime
-   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
+   >>> import datetime as dt
+   >>> d = dt.datetime(2010, 7, 4, 12, 15, 58)
    >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
    '2010-07-04 12:15:58'
 
index 7c81f52165972a5ab7ea96053891d9649bc88e32..b8aa04b9ab246d1ad04f34bbb56d9027bd2fa56a 100644 (file)
@@ -25,7 +25,7 @@
 Using Mock
 ----------
 
-Mock Patching Methods
+Mock patching methods
 ~~~~~~~~~~~~~~~~~~~~~
 
 Common uses for :class:`Mock` objects include:
@@ -71,7 +71,7 @@ the ``something`` method:
 
 
 
-Mock for Method Calls on an Object
+Mock for method calls on an object
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 In the last example we patched a method directly on an object to check that it
@@ -101,7 +101,7 @@ accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
 will raise a failure exception.
 
 
-Mocking Classes
+Mocking classes
 ~~~~~~~~~~~~~~~
 
 A common use case is to mock out classes instantiated by your code under test.
@@ -139,7 +139,7 @@ name is also propagated to attributes or methods of the mock:
     <MagicMock name='foo.method' id='...'>
 
 
-Tracking all Calls
+Tracking all calls
 ~~~~~~~~~~~~~~~~~~
 
 Often you want to track more than a single call to a method. The
@@ -176,7 +176,7 @@ possible to track nested calls where the parameters used to create ancestors are
     True
 
 
-Setting Return Values and Attributes
+Setting return values and attributes
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 Setting the return values on a mock object is trivially easy:
@@ -317,7 +317,7 @@ return an async function.
     >>> mock_instance.__aexit__.assert_awaited_once()
 
 
-Creating a Mock from an Existing Object
+Creating a mock from an existing object
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 One problem with over use of mocking is that it couples your tests to the
@@ -384,7 +384,7 @@ contents per file stored in a dictionary::
            assert file2.read() == "default"
 
 
-Patch Decorators
+Patch decorators
 ----------------
 
 .. note::
@@ -518,7 +518,7 @@ decorator individually to every method whose name starts with "test".
 
 .. _further-examples:
 
-Further Examples
+Further examples
 ----------------
 
 
@@ -614,13 +614,13 @@ attribute on the mock date class is then set to a lambda function that returns
 a real date. When the mock date class is called a real date will be
 constructed and returned by ``side_effect``. ::
 
-    >>> from datetime import date
+    >>> import datetime as dt
     >>> with patch('mymodule.date') as mock_date:
-    ...     mock_date.today.return_value = date(2010, 10, 8)
-    ...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
+    ...     mock_date.today.return_value = dt.date(2010, 10, 8)
+    ...     mock_date.side_effect = lambda *args, **kw: dt.date(*args, **kw)
     ...
-    ...     assert mymodule.date.today() == date(2010, 10, 8)
-    ...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
+    ...     assert mymodule.date.today() == dt.date(2010, 10, 8)
+    ...     assert mymodule.date(2009, 6, 8) == dt.date(2009, 6, 8)
 
 Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
 module that *uses* it. See :ref:`where to patch <where-to-patch>`.
@@ -638,7 +638,7 @@ is discussed in `this blog entry
 <https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
 
 
-Mocking a Generator Method
+Mocking a generator method
 ~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 A Python generator is a function or method that uses the :keyword:`yield` statement
@@ -739,7 +739,7 @@ exception is raised in the setUp then tearDown is not called.
     >>> MyTest('test_foo').run()
 
 
-Mocking Unbound Methods
+Mocking unbound methods
 ~~~~~~~~~~~~~~~~~~~~~~~
 
 Sometimes a test needs to patch an *unbound method*, which means patching the
@@ -937,7 +937,7 @@ and the ``return_value`` will use your subclass automatically. That means all
 children of a ``CopyingMock`` will also have the type ``CopyingMock``.
 
 
-Nesting Patches
+Nesting patches
 ~~~~~~~~~~~~~~~
 
 Using patch as a context manager is nice, but if you do multiple patches you
index 8b3b3dcaa13447f8fcf0b0c5db34989d08b5c1f1..458e67dbe51dccd29caf151be0ba70ce6929a7da 100644 (file)
@@ -272,12 +272,12 @@ DateTime Objects
 
 A working example follows. The server code::
 
-   import datetime
+   import datetime as dt
    from xmlrpc.server import SimpleXMLRPCServer
    import xmlrpc.client
 
    def today():
-       today = datetime.datetime.today()
+       today = dt.datetime.today()
        return xmlrpc.client.DateTime(today)
 
    server = SimpleXMLRPCServer(("localhost", 8000))
@@ -288,14 +288,14 @@ A working example follows. The server code::
 The client code for the preceding server::
 
    import xmlrpc.client
-   import datetime
+   import datetime as dt
 
    proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
 
    today = proxy.today()
-   # convert the ISO8601 string to a datetime object
-   converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
-   print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
+   # convert the ISO 8601 string to a datetime object
+   converted = dt.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
+   print(f"Today: {converted.strftime('%d.%m.%Y, %H:%M')}")
 
 .. _binary-objects:
 
index 2c130785be0db092dbc33aea2228ef07ec1d5359..5702257dfe2eba06517e259d7b82b679ac34361c 100644 (file)
@@ -69,7 +69,7 @@ servers written in Python.  Servers can either be free standing, using
 
 .. _simple-xmlrpc-servers:
 
-SimpleXMLRPCServer Objects
+SimpleXMLRPCServer objects
 --------------------------
 
 The :class:`SimpleXMLRPCServer` class is based on
@@ -140,7 +140,7 @@ alone XML-RPC servers.
 
 .. _simplexmlrpcserver-example:
 
-SimpleXMLRPCServer Example
+SimpleXMLRPCServer example
 ^^^^^^^^^^^^^^^^^^^^^^^^^^
 Server code::
 
@@ -231,7 +231,7 @@ a server allowing dotted names and registering a multicall function.
 
 ::
 
-    import datetime
+    import datetime as dt
 
     class ExampleService:
         def getData(self):
@@ -240,7 +240,7 @@ a server allowing dotted names and registering a multicall function.
         class currentTime:
             @staticmethod
             def getCurrentTime():
-                return datetime.datetime.now()
+                return dt.datetime.now()
 
     with SimpleXMLRPCServer(("localhost", 8000)) as server:
         server.register_function(pow)
@@ -387,7 +387,7 @@ to HTTP GET requests.  Servers can either be free standing, using
 
 .. _doc-xmlrpc-servers:
 
-DocXMLRPCServer Objects
+DocXMLRPCServer objects
 -----------------------
 
 The :class:`DocXMLRPCServer` class is derived from :class:`SimpleXMLRPCServer`
index cba08d6614fc08abd0b861b9beef7286f7b020fd..f5d3ade478ffb22f987120f1f883b4886a1ebdec 100644 (file)
@@ -37,24 +37,24 @@ the constructor, the :meth:`datetime.replace <datetime.datetime.replace>`
 method or :meth:`datetime.astimezone <datetime.datetime.astimezone>`::
 
     >>> from zoneinfo import ZoneInfo
-    >>> from datetime import datetime, timedelta
+    >>> import datetime as dt
 
-    >>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
-    >>> print(dt)
+    >>> when = dt.datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
+    >>> print(when)
     2020-10-31 12:00:00-07:00
 
-    >>> dt.tzname()
+    >>> when.tzname()
     'PDT'
 
 Datetimes constructed in this way are compatible with datetime arithmetic and
 handle daylight saving time transitions with no further intervention::
 
-    >>> dt_add = dt + timedelta(days=1)
+    >>> when_add = when + dt.timedelta(days=1)
 
-    >>> print(dt_add)
+    >>> print(when_add)
     2020-11-01 12:00:00-08:00
 
-    >>> dt_add.tzname()
+    >>> when_add.tzname()
     'PST'
 
 These time zones also support the :attr:`~datetime.datetime.fold` attribute
@@ -63,26 +63,25 @@ times (such as a daylight saving time to standard time transition), the offset
 from *before* the transition is used when ``fold=0``, and the offset *after*
 the transition is used when ``fold=1``, for example::
 
-    >>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
-    >>> print(dt)
+    >>> when = dt.datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
+    >>> print(when)
     2020-11-01 01:00:00-07:00
 
-    >>> print(dt.replace(fold=1))
+    >>> print(when.replace(fold=1))
     2020-11-01 01:00:00-08:00
 
 When converting from another time zone, the fold will be set to the correct
 value::
 
-    >>> from datetime import timezone
     >>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
-    >>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)
+    >>> when_utc = dt.datetime(2020, 11, 1, 8, tzinfo=dt.timezone.utc)
 
     >>> # Before the PDT -> PST transition
-    >>> print(dt_utc.astimezone(LOS_ANGELES))
+    >>> print(when_utc.astimezone(LOS_ANGELES))
     2020-11-01 01:00:00-07:00
 
     >>> # After the PDT -> PST transition
-    >>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
+    >>> print((when_utc + dt.timedelta(hours=1)).astimezone(LOS_ANGELES))
     2020-11-01 01:00:00-08:00
 
 Data sources
@@ -276,8 +275,8 @@ the note on usage in the attribute documentation)::
     >>> str(zone)
     'Pacific/Kwajalein'
 
-    >>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)
-    >>> f"{dt.isoformat()} [{dt.tzinfo}]"
+    >>> when = dt.datetime(2020, 4, 1, 3, 15, tzinfo=zone)
+    >>> f"{when.isoformat()} [{when.tzinfo}]"
     '2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'
 
 For objects constructed from a file without specifying a ``key`` parameter,
index 342c1a00193959fe9c0f1a9b7093c93a8e26e12f..e7c641044740504b67f11072093f0bd5ab2f9be1 100644 (file)
@@ -1,13 +1,13 @@
 .. _tut-brieftour:
 
 **********************************
-Brief Tour of the Standard Library
+Brief tour of the standard library
 **********************************
 
 
 .. _tut-os-interface:
 
-Operating System Interface
+Operating system interface
 ==========================
 
 The :mod:`os` module provides dozens of functions for interacting with the
@@ -47,7 +47,7 @@ a higher level interface that is easier to use::
 
 .. _tut-file-wildcards:
 
-File Wildcards
+File wildcards
 ==============
 
 The :mod:`glob` module provides a function for making file lists from directory
@@ -60,7 +60,7 @@ wildcard searches::
 
 .. _tut-command-line-arguments:
 
-Command Line Arguments
+Command-line arguments
 ======================
 
 Common utility scripts often need to process command line arguments. These
@@ -97,7 +97,7 @@ to ``['alpha.txt', 'beta.txt']``.
 
 .. _tut-stderr:
 
-Error Output Redirection and Program Termination
+Error output redirection and program termination
 ================================================
 
 The :mod:`sys` module also has attributes for *stdin*, *stdout*, and *stderr*.
@@ -112,7 +112,7 @@ The most direct way to terminate a script is to use ``sys.exit()``.
 
 .. _tut-string-pattern-matching:
 
-String Pattern Matching
+String pattern matching
 =======================
 
 The :mod:`re` module provides regular expression tools for advanced string
@@ -175,7 +175,7 @@ computations.
 
 .. _tut-internet-access:
 
-Internet Access
+Internet access
 ===============
 
 There are a number of modules for accessing the internet and processing internet
@@ -206,7 +206,7 @@ from URLs and :mod:`smtplib` for sending mail::
 
 .. _tut-dates-and-times:
 
-Dates and Times
+Dates and times
 ===============
 
 The :mod:`datetime` module supplies classes for manipulating dates and times in
@@ -216,15 +216,15 @@ formatting and manipulation.  The module also supports objects that are timezone
 aware. ::
 
    >>> # dates are easily constructed and formatted
-   >>> from datetime import date
-   >>> now = date.today()
+   >>> import datetime as dt
+   >>> now = dt.date.today()
    >>> now
    datetime.date(2003, 12, 2)
    >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
    '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
 
    >>> # dates support calendar arithmetic
-   >>> birthday = date(1964, 7, 31)
+   >>> birthday = dt.date(1964, 7, 31)
    >>> age = now - birthday
    >>> age.days
    14368
@@ -232,7 +232,7 @@ aware. ::
 
 .. _tut-data-compression:
 
-Data Compression
+Data compression
 ================
 
 Common data archiving and compression formats are directly supported by modules
@@ -254,7 +254,7 @@ including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`lzma`, :mod:`zipfile` and
 
 .. _tut-performance-measurement:
 
-Performance Measurement
+Performance measurement
 =======================
 
 Some Python users develop a deep interest in knowing the relative performance of
@@ -278,7 +278,7 @@ larger blocks of code.
 
 .. _tut-quality-control:
 
-Quality Control
+Quality control
 ===============
 
 One approach for developing high quality software is to write tests for each
@@ -324,7 +324,7 @@ file::
 
 .. _tut-batteries-included:
 
-Batteries Included
+Batteries included
 ==================
 
 Python has a "batteries included" philosophy.  This is best seen through the
index f43692b3dce9e8d6e74e2ed2a89d2a2afc95f86d..43ab19037d262736586374dfcd395444b12af80a 100644 (file)
@@ -1698,8 +1698,8 @@ current local date.
 Once created, instances of the date/time classes are all immutable. There are a
 number of methods for producing formatted strings from objects::
 
-   >>> import datetime
-   >>> now = datetime.datetime.now()
+   >>> import datetime as dt
+   >>> now = dt.datetime.now()
    >>> now.isoformat()
    '2002-12-30T21:27:03.994956'
    >>> now.ctime()  # Only available on date, datetime
@@ -1710,10 +1710,10 @@ number of methods for producing formatted strings from objects::
 The :meth:`~datetime.datetime.replace` method allows modifying one or more fields  of a
 :class:`~datetime.date` or :class:`~datetime.datetime` instance, returning a new instance::
 
-   >>> d = datetime.datetime.now()
+   >>> d = dt.datetime.now()
    >>> d
    datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
-   >>> d.replace(year=2001, hour = 12)
+   >>> d.replace(year=2001, hour=12)
    datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
    >>>
 
index 9b8f36862c1335fe95aec79fab992dad8ea4cc60..03e612fb651e71b725ea52e228f08380489e5d85 100644 (file)
@@ -1313,10 +1313,10 @@ complete list of changes, or look through the SVN logs for all the details.
   by Josh Spoerri. It uses the same format characters as :func:`time.strptime` and
   :func:`time.strftime`::
 
-     from datetime import datetime
+     import datetime as dt
 
-     ts = datetime.strptime('10:13:15 2006-03-07',
-                            '%H:%M:%S %Y-%m-%d')
+     ts = dt.datetime.strptime('10:13:15 2006-03-07',
+                               '%H:%M:%S %Y-%m-%d')
 
 * The :meth:`SequenceMatcher.get_matching_blocks` method in the :mod:`difflib`
   module now guarantees to return a minimal list of blocks describing matching
index f5e3a47037c65fa83d375779df3e71d6b0d8dd5b..1215601a09d681c74cbc836f6fcdf20329c85ba9 100644 (file)
@@ -2822,10 +2822,10 @@ Using the module is simple::
 
     import sys
     import plistlib
-    import datetime
+    import datetime as dt
 
     # Create data structure
-    data_struct = dict(lastAccessed=datetime.datetime.now(),
+    data_struct = dict(lastAccessed=dt.datetime.now(),
                        version=1,
                        categories=('Personal','Shared','Private'))
 
index 3b13d90f7692cd4632e31d0b530040c6dd848984..48c461d891e8614c216e0c9b94eb033cd5778732 100644 (file)
@@ -992,12 +992,12 @@ datetime and time
   offset and timezone name. This makes it easier to create timezone-aware
   datetime objects::
 
-    >>> from datetime import datetime, timezone
+    >>> import datetime as dt
 
-    >>> datetime.now(timezone.utc)
+    >>> dt.datetime.now(dt.timezone.utc)
     datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)
 
-    >>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
+    >>> dt.datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
     datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
 
 * Also, :class:`~datetime.timedelta` objects can now be multiplied by
index 545a17aecab8ee3940a35c79a92269de1d1d67e0..91cd23f6f2bbb95beb76ddf13039ba9fb2374d63 100644 (file)
@@ -50,7 +50,6 @@ For full details, see the :ref:`changelog <changelog>`.
 
 .. testsetup::
 
-   from datetime import date
    from math import cos, radians
    from unicodedata import normalize
    import re
@@ -259,15 +258,16 @@ Added an ``=`` specifier to :term:`f-string`\s. An f-string such as
 ``f'{expr=}'`` will expand to the text of the expression, an equal sign,
 then the representation of the evaluated expression.  For example:
 
+  >>> import datetime as dt
   >>> user = 'eric_idle'
-  >>> member_since = date(1975, 7, 31)
+  >>> member_since = dt.date(1975, 7, 31)
   >>> f'{user=} {member_since=}'
   "user='eric_idle' member_since=datetime.date(1975, 7, 31)"
 
 The usual :ref:`f-string format specifiers <f-strings>` allow more
 control over how the result of the expression is displayed::
 
-  >>> delta = date.today() - member_since
+  >>> delta = dt.date.today() - member_since
   >>> f'{user=!s}  {delta.days=:,d}'
   'user=eric_idle  delta.days=16,075'
 
index 40d4a27bff9fee5ce4d9d0aaf6cdf312f36ced84..49a52b7504bc9518b3431d5990aae8f0c310dd0e 100644 (file)
@@ -282,20 +282,20 @@ the standard library. It adds :class:`zoneinfo.ZoneInfo`, a concrete
 Example::
 
     >>> from zoneinfo import ZoneInfo
-    >>> from datetime import datetime, timedelta
+    >>> import datetime as dt
 
     >>> # Daylight saving time
-    >>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
-    >>> print(dt)
+    >>> when = dt.datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
+    >>> print(when)
     2020-10-31 12:00:00-07:00
-    >>> dt.tzname()
+    >>> when.tzname()
     'PDT'
 
     >>> # Standard time
-    >>> dt += timedelta(days=7)
-    >>> print(dt)
+    >>> when += dt.timedelta(days=7)
+    >>> print(when)
     2020-11-07 12:00:00-08:00
-    >>> print(dt.tzname())
+    >>> print(when.tzname())
     PST
 
 
index 3c6a6b7bdc44d299832fa0d12eb04ea8ab757172..01c7aa96261abecd1683c5adf333006638255192 100644 (file)
@@ -21,7 +21,7 @@ datetime.datetime objects.
 
 Generate Plist example:
 
-    import datetime
+    import datetime as dt
     import plistlib
 
     pl = dict(
@@ -37,7 +37,7 @@ Generate Plist example:
         ),
         someData = b"<binary gunk>",
         someMoreData = b"<lots of binary gunk>" * 10,
-        aDate = datetime.datetime.now()
+        aDate = dt.datetime.now()
     )
     print(plistlib.dumps(pl).decode())