[3.13] Docs: replace all datetime imports with import datetime as dt (GH-145640) (#146259)

Docs: replace all `datetime` imports with `import datetime as dt` (GH-145640)
(cherry picked from commit 83360b5869)

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2026-03-21 19:41:50 +01:00 committed by GitHub
parent 29303db78c
commit 5d71935bb3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 158 additions and 160 deletions

View 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.
@ -1538,8 +1538,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()

View file

@ -1536,10 +1536,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
@ -3606,7 +3606,6 @@ detailed information.
.. code-block:: python3
import datetime
import logging
import random
import sys
@ -3841,7 +3840,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.
@ -3849,7 +3848,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
@ -3867,7 +3866,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:

View 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():

View file

@ -4,7 +4,7 @@
.. _asyncio-event-loop:
==========
Event Loop
Event loop
==========
**Source code:** :source:`Lib/asyncio/events.py`,
@ -99,7 +99,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:
@ -355,7 +355,7 @@ clocks to track time.
The :func:`asyncio.sleep` function.
Creating Futures and Tasks
Creating futures and tasks
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. method:: loop.create_future()
@ -946,7 +946,7 @@ Transferring files
.. versionadded:: 3.7
TLS Upgrade
TLS upgrade
^^^^^^^^^^^
.. method:: loop.start_tls(transport, protocol, \
@ -1408,7 +1408,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.
@ -1511,7 +1511,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
@ -1649,7 +1649,7 @@ async/await code consider using the high-level
are going to be used to construct shell commands.
Callback Handles
Callback handles
================
.. class:: Handle
@ -1692,7 +1692,7 @@ Callback Handles
.. versionadded:: 3.7
Server Objects
Server objects
==============
Server objects are created by :meth:`loop.create_server`,
@ -1835,7 +1835,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:
@ -1949,10 +1949,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:

View 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;

View file

@ -371,7 +371,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.

View 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`
@ -291,7 +291,7 @@ Creating Tasks
Added the *context* parameter.
Task Cancellation
Task cancellation
=================
Tasks can easily and safely be cancelled.
@ -315,7 +315,7 @@ remove the cancellation state.
.. _taskgroups:
Task Groups
Task groups
===========
Task groups combine a task creation API with a convenient
@ -414,7 +414,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
@ -485,13 +485,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)
@ -506,7 +506,7 @@ Sleeping
Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
Running Tasks Concurrently
Running tasks concurrently
==========================
.. awaitablefunction:: gather(*aws, return_exceptions=False)
@ -608,7 +608,7 @@ Running Tasks Concurrently
.. _eager-task-factory:
Eager Task Factory
Eager task factory
==================
.. function:: eager_task_factory(loop, coro, *, name=None, context=None)
@ -651,7 +651,7 @@ Eager Task Factory
.. versionadded:: 3.12
Shielding From Cancellation
Shielding from cancellation
===========================
.. awaitablefunction:: shield(aw)
@ -881,7 +881,7 @@ Timeouts
Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`.
Waiting Primitives
Waiting primitives
==================
.. function:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
@ -1001,7 +1001,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)
@ -1061,7 +1061,7 @@ Running in Threads
.. versionadded:: 3.9
Scheduling From Other Threads
Scheduling from other threads
=============================
.. function:: run_coroutine_threadsafe(coro, loop)
@ -1140,7 +1140,7 @@ Introspection
.. _asyncio-task-obj:
Task Object
Task object
===========
.. class:: Task(coro, *, loop=None, name=None, context=None, eager_start=False)

View file

@ -358,7 +358,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:
@ -586,7 +586,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":
@ -637,7 +637,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**
@ -686,7 +686,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

View file

@ -61,7 +61,7 @@ are not normal Python classes. See
---------------
Module Contents
Module contents
---------------
:class:`EnumType`
@ -166,7 +166,7 @@ Module Contents
---------------
Data Types
Data types
----------
@ -322,7 +322,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
@ -333,7 +333,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']
@ -940,7 +940,7 @@ Supported ``_sunder_`` names
---------------
Utilities and Decorators
Utilities and decorators
------------------------
.. class:: auto

View file

@ -184,7 +184,7 @@ Examples
Generating a plist::
import datetime
import datetime as dt
import plistlib
pl = dict(
@ -200,7 +200,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())

View file

@ -2304,7 +2304,7 @@ This section shows recipes for common adapters and converters.
.. testcode::
import datetime
import datetime as dt
import sqlite3
def adapt_date_iso(val):
@ -2319,21 +2319,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)
@ -2342,17 +2342,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

View file

@ -69,7 +69,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
------------------------------------
@ -358,7 +358,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).
@ -368,12 +368,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`).
@ -1043,7 +1043,7 @@ Constants
:attr:`TLSVersion.TLSv1_3` are deprecated.
SSL Sockets
SSL sockets
-----------
.. class:: SSLSocket(socket.socket)
@ -1404,7 +1404,7 @@ SSL sockets also have the following additional methods and attributes:
.. versionadded:: 3.6
SSL Contexts
SSL contexts
------------
.. versionadded:: 3.2
@ -2520,7 +2520,7 @@ thus several things you need to be aware of:
as well.
Memory BIO Support
Memory BIO support
------------------
.. versionadded:: 3.5

View 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
@ -190,7 +190,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
@ -299,7 +299,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
@ -743,8 +743,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'

View file

@ -26,7 +26,7 @@
Using Mock
----------
Mock Patching Methods
Mock patching methods
~~~~~~~~~~~~~~~~~~~~~
Common uses for :class:`Mock` objects include:
@ -72,7 +72,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
@ -102,7 +102,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.
@ -140,7 +140,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
@ -177,7 +177,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:
@ -318,7 +318,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
@ -385,7 +385,7 @@ contents per file stored in a dictionary::
assert file2.read() == "default"
Patch Decorators
Patch decorators
----------------
.. note::
@ -519,7 +519,7 @@ decorator individually to every method whose name starts with "test".
.. _further-examples:
Further Examples
Further examples
----------------
@ -615,13 +615,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>`.
@ -639,7 +639,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
@ -740,7 +740,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
@ -938,7 +938,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

View file

@ -275,12 +275,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))
@ -291,14 +291,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:

View file

@ -72,7 +72,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
@ -143,7 +143,7 @@ alone XML-RPC servers.
.. _simplexmlrpcserver-example:
SimpleXMLRPCServer Example
SimpleXMLRPCServer example
^^^^^^^^^^^^^^^^^^^^^^^^^^
Server code::
@ -234,7 +234,7 @@ a server allowing dotted names and registering a multicall function.
::
import datetime
import datetime as dt
class ExampleService:
def getData(self):
@ -243,7 +243,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)
@ -390,7 +390,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`

View file

@ -40,24 +40,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
@ -66,26 +66,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
@ -279,8 +278,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,

View 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

View 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)
>>>

View 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

View 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'))

View 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

View 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'

View 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

View file

@ -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())