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
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.
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()
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
.. code-block:: python3
- import datetime
import logging
import random
import sys
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.
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
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:
-""" 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.
"""
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():
.. _asyncio-event-loop:
==========
-Event Loop
+Event loop
==========
**Source code:** :source:`Lib/asyncio/events.py`,
.. _asyncio-event-loop-methods:
-Event Loop Methods
+Event loop methods
==================
Event loops have **low-level** APIs for the following:
The :func:`asyncio.sleep` function.
-Creating Futures and Tasks
+Creating futures and tasks
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. method:: loop.create_future()
.. versionadded:: 3.7
-TLS Upgrade
+TLS upgrade
^^^^^^^^^^^
.. method:: loop.start_tls(transport, protocol, \
:class:`~concurrent.futures.ThreadPoolExecutor`.
-Error Handling API
+Error handling API
^^^^^^^^^^^^^^^^^^
Allows customizing how exceptions are handled in the event loop.
The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
-Running Subprocesses
+Running subprocesses
^^^^^^^^^^^^^^^^^^^^
Methods described in this subsections are low-level. In regular
are going to be used to construct shell commands.
-Callback Handles
+Callback handles
================
.. class:: Handle
.. versionadded:: 3.7
-Server Objects
+Server objects
==============
Server objects are created by :meth:`loop.create_server`,
.. _asyncio-event-loops:
.. _asyncio-event-loop-implementations:
-Event Loop Implementations
+Event loop implementations
==========================
asyncio ships with two different event loop implementations:
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:
# 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;
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.
====================
-Coroutines and Tasks
+Coroutines and tasks
====================
This section outlines high-level asyncio APIs to work with coroutines
is :meth:`loop.run_in_executor`.
-Creating Tasks
+Creating tasks
==============
**Source code:** :source:`Lib/asyncio/tasks.py`
Added the *eager_start* parameter by passing on all *kwargs*.
-Task Cancellation
+Task cancellation
=================
Tasks can easily and safely be cancelled.
.. _taskgroups:
-Task Groups
+Task groups
===========
Task groups combine a task creation API with a convenient
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
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)
Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
-Running Tasks Concurrently
+Running tasks concurrently
==========================
.. awaitablefunction:: gather(*aws, return_exceptions=False)
.. _eager-task-factory:
-Eager Task Factory
+Eager task factory
==================
.. function:: eager_task_factory(loop, coro, *, name=None, context=None)
.. versionadded:: 3.12
-Shielding From Cancellation
+Shielding from cancellation
===========================
.. awaitablefunction:: shield(aw)
Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`.
-Waiting Primitives
+Waiting primitives
==================
.. function:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
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)
.. versionadded:: 3.9
-Scheduling From Other Threads
+Scheduling from other threads
=============================
.. function:: run_coroutine_threadsafe(coro, loop)
.. _asyncio-task-obj:
-Task Object
+Task object
===========
.. class:: Task(coro, *, loop=None, name=None, context=None, eager_start=False)
.. _sequence-matcher:
-SequenceMatcher Objects
+SequenceMatcher objects
-----------------------
The :class:`SequenceMatcher` class has this constructor:
.. _sequencematcher-examples:
-SequenceMatcher Examples
+SequenceMatcher examples
------------------------
This example compares two strings, considering blanks to be "junk":
.. _differ-objects:
-Differ Objects
+Differ objects
--------------
Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
.. _differ-examples:
-Differ Example
+Differ example
--------------
This example compares two texts. First we set up the texts, sequences of
---------------
-Module Contents
+Module contents
---------------
:class:`EnumType`
---------------
-Data Types
+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
... 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']
---------------
-Utilities and Decorators
+Utilities and decorators
------------------------
.. class:: auto
Generating a plist::
- import datetime
+ import datetime as dt
import plistlib
pl = dict(
),
someData = b"<binary gunk>",
someMoreData = b"<lots of binary gunk>" * 10,
- aDate = datetime.datetime.now()
+ aDate = dt.datetime.now()
)
print(plistlib.dumps(pl).decode())
.. testcode::
- import datetime
+ import datetime as dt
import sqlite3
def adapt_date_iso(val):
"""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)
.. 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
Use of deprecated constants and functions result in deprecation warnings.
-Functions, Constants, and Exceptions
+Functions, constants, and exceptions
------------------------------------
.. 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).
.. 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`).
:attr:`TLSVersion.TLSv1_3` are deprecated.
-SSL Sockets
+SSL sockets
-----------
.. class:: SSLSocket(socket.socket)
.. versionadded:: 3.6
-SSL Contexts
+SSL contexts
------------
.. versionadded:: 3.2
as well.
-Memory BIO Support
+Memory BIO support
------------------
.. versionadded:: 3.5
.. _string-formatting:
-Custom String Formatting
+Custom string formatting
------------------------
The built-in string class provides the ability to do complex variable
.. _formatstrings:
-Format String Syntax
+Format string syntax
--------------------
The :meth:`str.format` method and the :class:`Formatter` class share the same
.. _formatspec:
-Format Specification Mini-Language
+Format specification mini-language
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"Format specifications" are used within replacement fields contained within a
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'
Using Mock
----------
-Mock Patching Methods
+Mock patching methods
~~~~~~~~~~~~~~~~~~~~~
Common uses for :class:`Mock` objects include:
-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
will raise a failure exception.
-Mocking Classes
+Mocking classes
~~~~~~~~~~~~~~~
A common use case is to mock out classes instantiated by your code under test.
<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
True
-Setting Return Values and Attributes
+Setting return values and attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Setting the return values on a mock object is trivially easy:
>>> 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
assert file2.read() == "default"
-Patch Decorators
+Patch decorators
----------------
.. note::
.. _further-examples:
-Further Examples
+Further examples
----------------
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>`.
<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
>>> MyTest('test_foo').run()
-Mocking Unbound Methods
+Mocking unbound methods
~~~~~~~~~~~~~~~~~~~~~~~
Sometimes a test needs to patch an *unbound method*, which means patching the
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
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))
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:
.. _simple-xmlrpc-servers:
-SimpleXMLRPCServer Objects
+SimpleXMLRPCServer objects
--------------------------
The :class:`SimpleXMLRPCServer` class is based on
.. _simplexmlrpcserver-example:
-SimpleXMLRPCServer Example
+SimpleXMLRPCServer example
^^^^^^^^^^^^^^^^^^^^^^^^^^
Server code::
::
- import datetime
+ import datetime as dt
class ExampleService:
def getData(self):
class currentTime:
@staticmethod
def getCurrentTime():
- return datetime.datetime.now()
+ return dt.datetime.now()
with SimpleXMLRPCServer(("localhost", 8000)) as server:
server.register_function(pow)
.. _doc-xmlrpc-servers:
-DocXMLRPCServer Objects
+DocXMLRPCServer objects
-----------------------
The :class:`DocXMLRPCServer` class is derived from :class:`SimpleXMLRPCServer`
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
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
>>> 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,
.. _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
.. _tut-file-wildcards:
-File Wildcards
+File wildcards
==============
The :mod:`glob` module provides a function for making file lists from directory
.. _tut-command-line-arguments:
-Command Line Arguments
+Command-line arguments
======================
Common utility scripts often need to process command line arguments. These
.. _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*.
.. _tut-string-pattern-matching:
-String Pattern Matching
+String pattern matching
=======================
The :mod:`re` module provides regular expression tools for advanced string
.. _tut-internet-access:
-Internet Access
+Internet access
===============
There are a number of modules for accessing the internet and processing internet
.. _tut-dates-and-times:
-Dates and Times
+Dates and times
===============
The :mod:`datetime` module supplies classes for manipulating dates and times in
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
.. _tut-data-compression:
-Data Compression
+Data compression
================
Common data archiving and compression formats are directly supported by modules
.. _tut-performance-measurement:
-Performance Measurement
+Performance measurement
=======================
Some Python users develop a deep interest in knowing the relative performance of
.. _tut-quality-control:
-Quality Control
+Quality control
===============
One approach for developing high quality software is to write tests for each
.. _tut-batteries-included:
-Batteries Included
+Batteries included
==================
Python has a "batteries included" philosophy. This is best seen through the
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
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)
>>>
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
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'))
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
.. testsetup::
- from datetime import date
from math import cos, radians
from unicodedata import normalize
import re
``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'
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
Generate Plist example:
- import datetime
+ import datetime as dt
import plistlib
pl = dict(
),
someData = b"<binary gunk>",
someMoreData = b"<lots of binary gunk>" * 10,
- aDate = datetime.datetime.now()
+ aDate = dt.datetime.now()
)
print(plistlib.dumps(pl).decode())