Docs: replace all `datetime` imports with `import datetime as dt` (#145640)
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index 8bd2bc9..ff34bb5 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -1074,7 +1074,7 @@
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 a list of things to
remember before diving further:
* Performance characteristics vary across Python implementations. This FAQ
diff --git a/Doc/howto/enum.rst b/Doc/howto/enum.rst
index 93850b5..5260c2c 100644
--- a/Doc/howto/enum.rst
+++ b/Doc/howto/enum.rst
@@ -105,8 +105,8 @@
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 @@
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()
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index b87ac93..21df6ba 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -1549,10 +1549,10 @@
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 @@
.. code-block:: python3
- import datetime
import logging
import random
import sys
@@ -3851,7 +3850,7 @@
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 @@
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 @@
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:
diff --git a/Doc/includes/diff.py b/Doc/includes/diff.py
index 001619f..bc4bd58 100644
--- a/Doc/includes/diff.py
+++ b/Doc/includes/diff.py
@@ -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():
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index bdb24b3..d1a5b4e 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -4,7 +4,7 @@
.. _asyncio-event-loop:
==========
-Event Loop
+Event loop
==========
**Source code:** :source:`Lib/asyncio/events.py`,
@@ -105,7 +105,7 @@
.. _asyncio-event-loop-methods:
-Event Loop Methods
+Event loop methods
==================
Event loops have **low-level** APIs for the following:
@@ -361,7 +361,7 @@
The :func:`asyncio.sleep` function.
-Creating Futures and Tasks
+Creating futures and tasks
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. method:: loop.create_future()
@@ -962,7 +962,7 @@
.. versionadded:: 3.7
-TLS Upgrade
+TLS upgrade
^^^^^^^^^^^
.. method:: loop.start_tls(transport, protocol, \
@@ -1431,7 +1431,7 @@
:class:`~concurrent.futures.ThreadPoolExecutor`.
-Error Handling API
+Error handling API
^^^^^^^^^^^^^^^^^^
Allows customizing how exceptions are handled in the event loop.
@@ -1534,7 +1534,7 @@
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 @@
are going to be used to construct shell commands.
-Callback Handles
+Callback handles
================
.. class:: Handle
@@ -1715,7 +1715,7 @@
.. versionadded:: 3.7
-Server Objects
+Server objects
==============
Server objects are created by :meth:`loop.create_server`,
@@ -1858,7 +1858,7 @@
.. _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 @@
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:
diff --git a/Doc/library/asyncio-protocol.rst b/Doc/library/asyncio-protocol.rst
index 5208f14..58f77fe 100644
--- a/Doc/library/asyncio-protocol.rst
+++ b/Doc/library/asyncio-protocol.rst
@@ -1037,7 +1037,7 @@
# 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;
diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst
index cb9ddc0..a651464 100644
--- a/Doc/library/asyncio-subprocess.rst
+++ b/Doc/library/asyncio-subprocess.rst
@@ -359,7 +359,7 @@
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.
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index e2a6752..4e60eee 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -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 @@
is :meth:`loop.run_in_executor`.
-Creating Tasks
+Creating tasks
==============
**Source code:** :source:`Lib/asyncio/tasks.py`
@@ -300,7 +300,7 @@
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 @@
.. _taskgroups:
-Task Groups
+Task groups
===========
Task groups combine a task creation API with a convenient
@@ -427,7 +427,7 @@
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 @@
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 @@
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 @@
.. _eager-task-factory:
-Eager Task Factory
+Eager task factory
==================
.. function:: eager_task_factory(loop, coro, *, name=None, context=None)
@@ -664,7 +664,7 @@
.. versionadded:: 3.12
-Shielding From Cancellation
+Shielding from cancellation
===========================
.. awaitablefunction:: shield(aw)
@@ -894,7 +894,7 @@
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 @@
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 @@
.. versionadded:: 3.9
-Scheduling From Other Threads
+Scheduling from other threads
=============================
.. function:: run_coroutine_threadsafe(coro, loop)
@@ -1198,7 +1198,7 @@
.. _asyncio-task-obj:
-Task Object
+Task object
===========
.. class:: Task(coro, *, loop=None, name=None, context=None, eager_start=False)
diff --git a/Doc/library/difflib.rst b/Doc/library/difflib.rst
index e56c4f5..8b812c1 100644
--- a/Doc/library/difflib.rst
+++ b/Doc/library/difflib.rst
@@ -362,7 +362,7 @@
.. _sequence-matcher:
-SequenceMatcher Objects
+SequenceMatcher objects
-----------------------
The :class:`SequenceMatcher` class has this constructor:
@@ -590,7 +590,7 @@
.. _sequencematcher-examples:
-SequenceMatcher Examples
+SequenceMatcher examples
------------------------
This example compares two strings, considering blanks to be "junk":
@@ -641,7 +641,7 @@
.. _differ-objects:
-Differ Objects
+Differ objects
--------------
Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
@@ -690,7 +690,7 @@
.. _differ-examples:
-Differ Example
+Differ example
--------------
This example compares two texts. First we set up the texts, sequences of
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index 8a8a2ed..0a1d2a0 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -56,7 +56,7 @@
---------------
-Module Contents
+Module contents
---------------
:class:`EnumType`
@@ -161,7 +161,7 @@
---------------
-Data Types
+Data types
----------
@@ -341,7 +341,7 @@
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 @@
... 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 @@
---------------
-Utilities and Decorators
+Utilities and decorators
------------------------
.. class:: auto
diff --git a/Doc/library/plistlib.rst b/Doc/library/plistlib.rst
index e5fc19f..fa15cd4 100644
--- a/Doc/library/plistlib.rst
+++ b/Doc/library/plistlib.rst
@@ -180,7 +180,7 @@
Generating a plist::
- import datetime
+ import datetime as dt
import plistlib
pl = dict(
@@ -196,7 +196,7 @@
),
someData = b"<binary gunk>",
someMoreData = b"<lots of binary gunk>" * 10,
- aDate = datetime.datetime.now()
+ aDate = dt.datetime.now()
)
print(plistlib.dumps(pl).decode())
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index 40d103c..ff1676c 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -2285,7 +2285,7 @@
.. testcode::
- import datetime
+ import datetime as dt
import sqlite3
def adapt_date_iso(val):
@@ -2300,21 +2300,21 @@
"""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 @@
.. 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
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index e83c2c9..f2c35d1 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -67,7 +67,7 @@
Use of deprecated constants and functions result in deprecation warnings.
-Functions, Constants, and Exceptions
+Functions, constants, and exceptions
------------------------------------
@@ -374,7 +374,7 @@
.. 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 @@
.. 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 @@
:attr:`TLSVersion.TLSv1_3` are deprecated.
-SSL Sockets
+SSL sockets
-----------
.. class:: SSLSocket(socket.socket)
@@ -1462,7 +1462,7 @@
.. versionadded:: 3.6
-SSL Contexts
+SSL contexts
------------
.. versionadded:: 3.2
@@ -2653,7 +2653,7 @@
as well.
-Memory BIO Support
+Memory BIO support
------------------
.. versionadded:: 3.5
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 8096d90..08ccdfa 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -82,7 +82,7 @@
.. _string-formatting:
-Custom String Formatting
+Custom string formatting
------------------------
The built-in string class provides the ability to do complex variable
@@ -192,7 +192,7 @@
.. _formatstrings:
-Format String Syntax
+Format string syntax
--------------------
The :meth:`str.format` method and the :class:`Formatter` class share the same
@@ -304,7 +304,7 @@
.. _formatspec:
-Format Specification Mini-Language
+Format specification mini-language
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"Format specifications" are used within replacement fields contained within a
@@ -759,8 +759,8 @@
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'
diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst
index 7c81f52..b8aa04b 100644
--- a/Doc/library/unittest.mock-examples.rst
+++ b/Doc/library/unittest.mock-examples.rst
@@ -25,7 +25,7 @@
Using Mock
----------
-Mock Patching Methods
+Mock patching methods
~~~~~~~~~~~~~~~~~~~~~
Common uses for :class:`Mock` objects include:
@@ -71,7 +71,7 @@
-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 @@
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 @@
<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 @@
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 @@
>>> 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 @@
assert file2.read() == "default"
-Patch Decorators
+Patch decorators
----------------
.. note::
@@ -518,7 +518,7 @@
.. _further-examples:
-Further Examples
+Further examples
----------------
@@ -614,13 +614,13 @@
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 @@
<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 @@
>>> 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 @@
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
diff --git a/Doc/library/xmlrpc.client.rst b/Doc/library/xmlrpc.client.rst
index 8b3b3dc..458e67d 100644
--- a/Doc/library/xmlrpc.client.rst
+++ b/Doc/library/xmlrpc.client.rst
@@ -272,12 +272,12 @@
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 @@
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:
diff --git a/Doc/library/xmlrpc.server.rst b/Doc/library/xmlrpc.server.rst
index 2c13078..5702257 100644
--- a/Doc/library/xmlrpc.server.rst
+++ b/Doc/library/xmlrpc.server.rst
@@ -69,7 +69,7 @@
.. _simple-xmlrpc-servers:
-SimpleXMLRPCServer Objects
+SimpleXMLRPCServer objects
--------------------------
The :class:`SimpleXMLRPCServer` class is based on
@@ -140,7 +140,7 @@
.. _simplexmlrpcserver-example:
-SimpleXMLRPCServer Example
+SimpleXMLRPCServer example
^^^^^^^^^^^^^^^^^^^^^^^^^^
Server code::
@@ -231,7 +231,7 @@
::
- import datetime
+ import datetime as dt
class ExampleService:
def getData(self):
@@ -240,7 +240,7 @@
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 @@
.. _doc-xmlrpc-servers:
-DocXMLRPCServer Objects
+DocXMLRPCServer objects
-----------------------
The :class:`DocXMLRPCServer` class is derived from :class:`SimpleXMLRPCServer`
diff --git a/Doc/library/zoneinfo.rst b/Doc/library/zoneinfo.rst
index cba08d6..f5d3ade 100644
--- a/Doc/library/zoneinfo.rst
+++ b/Doc/library/zoneinfo.rst
@@ -37,24 +37,24 @@
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 @@
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 @@
>>> 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,
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
index 342c1a0..e7c6410 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -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 @@
.. _tut-file-wildcards:
-File Wildcards
+File wildcards
==============
The :mod:`glob` module provides a function for making file lists from directory
@@ -60,7 +60,7 @@
.. _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 @@
.. _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 @@
.. _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 @@
.. _tut-internet-access:
-Internet Access
+Internet access
===============
There are a number of modules for accessing the internet and processing internet
@@ -206,7 +206,7 @@
.. _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 @@
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 @@
.. _tut-data-compression:
-Data Compression
+Data compression
================
Common data archiving and compression formats are directly supported by modules
@@ -254,7 +254,7 @@
.. _tut-performance-measurement:
-Performance Measurement
+Performance measurement
=======================
Some Python users develop a deep interest in knowing the relative performance of
@@ -278,7 +278,7 @@
.. _tut-quality-control:
-Quality Control
+Quality control
===============
One approach for developing high quality software is to write tests for each
@@ -324,7 +324,7 @@
.. _tut-batteries-included:
-Batteries Included
+Batteries included
==================
Python has a "batteries included" philosophy. This is best seen through the
diff --git a/Doc/whatsnew/2.3.rst b/Doc/whatsnew/2.3.rst
index f43692b..43ab190 100644
--- a/Doc/whatsnew/2.3.rst
+++ b/Doc/whatsnew/2.3.rst
@@ -1698,8 +1698,8 @@
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 @@
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)
>>>
diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst
index 9b8f368..03e612f 100644
--- a/Doc/whatsnew/2.5.rst
+++ b/Doc/whatsnew/2.5.rst
@@ -1313,10 +1313,10 @@
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
diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst
index f5e3a47..1215601 100644
--- a/Doc/whatsnew/2.6.rst
+++ b/Doc/whatsnew/2.6.rst
@@ -2822,10 +2822,10 @@
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'))
diff --git a/Doc/whatsnew/3.2.rst b/Doc/whatsnew/3.2.rst
index 3b13d90..48c461d 100644
--- a/Doc/whatsnew/3.2.rst
+++ b/Doc/whatsnew/3.2.rst
@@ -992,12 +992,12 @@
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
diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst
index 545a17a..91cd23f 100644
--- a/Doc/whatsnew/3.8.rst
+++ b/Doc/whatsnew/3.8.rst
@@ -50,7 +50,6 @@
.. testsetup::
- from datetime import date
from math import cos, radians
from unicodedata import normalize
import re
@@ -259,15 +258,16 @@
``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'
diff --git a/Doc/whatsnew/3.9.rst b/Doc/whatsnew/3.9.rst
index 40d4a27..49a52b7 100644
--- a/Doc/whatsnew/3.9.rst
+++ b/Doc/whatsnew/3.9.rst
@@ -282,20 +282,20 @@
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
diff --git a/Lib/plistlib.py b/Lib/plistlib.py
index 3c6a6b7..01c7aa9 100644
--- a/Lib/plistlib.py
+++ b/Lib/plistlib.py
@@ -21,7 +21,7 @@
Generate Plist example:
- import datetime
+ import datetime as dt
import plistlib
pl = dict(
@@ -37,7 +37,7 @@
),
someData = b"<binary gunk>",
someMoreData = b"<lots of binary gunk>" * 10,
- aDate = datetime.datetime.now()
+ aDate = dt.datetime.now()
)
print(plistlib.dumps(pl).decode())