summaryrefslogtreecommitdiff
path: root/docs/topics
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2021-09-09 15:15:44 +0200
committerCarlton Gibson <carlton.gibson@noumenal.es>2021-09-16 12:11:05 +0200
commit306607d5b99b6eca6ae2c1e726d8eb32b9b2ca1b (patch)
tree607d1b06feafaf28fc2e09c70652d30659707537 /docs/topics
parent7132d17de1399345a38858c20221850bdef43d0e (diff)
Fixed #32365 -- Made zoneinfo the default timezone implementation.
Thanks to Adam Johnson, Aymeric Augustin, David Smith, Mariusz Felisiak, Nick Pope, and Paul Ganssle for reviews.
Diffstat (limited to 'docs/topics')
-rw-r--r--docs/topics/i18n/timezones.txt108
1 files changed, 55 insertions, 53 deletions
diff --git a/docs/topics/i18n/timezones.txt b/docs/topics/i18n/timezones.txt
index 5b475bd44f..6eda217f56 100644
--- a/docs/topics/i18n/timezones.txt
+++ b/docs/topics/i18n/timezones.txt
@@ -19,10 +19,9 @@ practice to store data in UTC in your database. The main reason is daylight
saving time (DST). Many countries have a system of DST, where clocks are moved
forward in spring and backward in autumn. If you're working in local time,
you're likely to encounter errors twice a year, when the transitions happen.
-(The pytz_ documentation discusses `these issues`_ in greater detail.) This
-probably doesn't matter for your blog, but it's a problem if you over-bill or
-under-bill your customers by one hour, twice a year, every year. The solution
-to this problem is to use UTC in the code and use local time only when
+This probably doesn't matter for your blog, but it's a problem if you over bill
+or under bill your customers by one hour, twice a year, every year. The
+solution to this problem is to use UTC in the code and use local time only when
interacting with end users.
Time zone support is disabled by default. To enable it, set :setting:`USE_TZ =
@@ -32,15 +31,20 @@ True <USE_TZ>` in your settings file.
In Django 5.0, time zone support will be enabled by default.
-By default, time zone support uses pytz_, which is installed when you install
-Django; Django also supports the use of other time zone implementations like
-:mod:`zoneinfo` by passing :class:`~datetime.tzinfo` objects directly to
-functions in :mod:`django.utils.timezone`.
+Time zone support uses :mod:`zoneinfo`, which is part of the Python standard
+library from Python 3.9. The ``backports.zoneinfo`` package is automatically
+installed alongside Django if you are using Python 3.8.
.. versionchanged:: 3.2
Support for non-``pytz`` timezone implementations was added.
+.. versionchanged:: 4.0
+
+ :mod:`zoneinfo` was made the default timezone implementation. You may
+ continue to use `pytz`_ during the 4.x release cycle via the
+ :setting:`USE_DEPRECATED_PYTZ` setting.
+
.. note::
The default :file:`settings.py` file created by :djadmin:`django-admin
@@ -88,8 +92,8 @@ should be aware too. In this mode, the example above becomes::
Dealing with aware datetime objects isn't always intuitive. For instance,
the ``tzinfo`` argument of the standard datetime constructor doesn't work
reliably for time zones with DST. Using UTC is generally safe; if you're
- using other time zones, you should review the `pytz`_ documentation
- carefully.
+ using other time zones, you should review the :mod:`zoneinfo`
+ documentation carefully.
.. note::
@@ -113,8 +117,10 @@ receives one, it attempts to make it aware by interpreting it in the
:ref:`default time zone <default-current-time-zone>` and raises a warning.
Unfortunately, during DST transitions, some datetimes don't exist or are
-ambiguous. In such situations, pytz_ raises an exception. That's why you should
-always create aware datetime objects when time zone support is enabled.
+ambiguous. That's why you should always create aware datetime objects when time
+zone support is enabled. (See the :mod:`Using ZoneInfo section of the zoneinfo
+docs <zoneinfo>` for examples using the ``fold`` attribute to specify the
+offset that should apply to a datetime during a DST transition.)
In practice, this is rarely an issue. Django gives you aware datetime objects
in the models and forms, and most often, new datetime objects are created from
@@ -163,16 +169,16 @@ selection logic that makes sense for you.
Most websites that care about time zones ask users in which time zone they live
and store this information in the user's profile. For anonymous users, they use
-the time zone of their primary audience or UTC. pytz_ provides helpers_, like a
-list of time zones per country, that you can use to pre-select the most likely
-choices.
+the time zone of their primary audience or UTC.
+:func:`zoneinfo.available_timezones` provides a set of available timezones that
+you can use to build a map from likely locations to time zones.
Here's an example that stores the current timezone in the session. (It skips
error handling entirely for the sake of simplicity.)
Add the following middleware to :setting:`MIDDLEWARE`::
- import pytz
+ import zoneinfo
from django.utils import timezone
@@ -183,7 +189,7 @@ Add the following middleware to :setting:`MIDDLEWARE`::
def __call__(self, request):
tzname = request.session.get('django_timezone')
if tzname:
- timezone.activate(pytz.timezone(tzname))
+ timezone.activate(zoneinfo.ZoneInfo(tzname))
else:
timezone.deactivate()
return self.get_response(request)
@@ -192,12 +198,19 @@ Create a view that can set the current timezone::
from django.shortcuts import redirect, render
+ # Prepare a map of common locations to timezone choices you wish to offer.
+ common_timezones = {
+ 'London': 'Europe/London',
+ 'Paris': 'Europe/Paris',
+ 'New York': 'America/New_York',
+ }
+
def set_timezone(request):
if request.method == 'POST':
request.session['django_timezone'] = request.POST['timezone']
return redirect('/')
else:
- return render(request, 'template.html', {'timezones': pytz.common_timezones})
+ return render(request, 'template.html', {'timezones': common_timezones})
Include a form in ``template.html`` that will ``POST`` to this view:
@@ -209,8 +222,8 @@ Include a form in ``template.html`` that will ``POST`` to this view:
{% csrf_token %}
<label for="timezone">Time zone:</label>
<select name="timezone">
- {% for tz in timezones %}
- <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option>
+ {% for city, tz in timezones %}
+ <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ city }}</option>
{% endfor %}
</select>
<input type="submit" value="Set">
@@ -225,9 +238,8 @@ When you enable time zone support, Django interprets datetimes entered in
forms in the :ref:`current time zone <default-current-time-zone>` and returns
aware datetime objects in ``cleaned_data``.
-If the current time zone raises an exception for datetimes that don't exist or
-are ambiguous because they fall in a DST transition (the timezones provided by
-pytz_ do this), such datetimes will be reported as invalid values.
+Converted datetimes that don't exist or are ambiguous because they fall in a
+DST transition will be reported as invalid values.
.. _time-zones-in-templates:
@@ -583,20 +595,20 @@ Troubleshooting
None of this is true in a time zone aware environment::
>>> import datetime
- >>> import pytz
- >>> paris_tz = pytz.timezone("Europe/Paris")
- >>> new_york_tz = pytz.timezone("America/New_York")
- >>> paris = paris_tz.localize(datetime.datetime(2012, 3, 3, 1, 30))
- # This is the correct way to convert between time zones with pytz.
- >>> new_york = new_york_tz.normalize(paris.astimezone(new_york_tz))
+ >>> import zoneinfo
+ >>> paris_tz = zoneinfo.ZoneInfo("Europe/Paris")
+ >>> new_york_tz = zoneinfo.ZoneInfo("America/New_York")
+ >>> paris = datetime.datetime(2012, 3, 3, 1, 30, tzinfo=paris_tz)
+ # This is the correct way to convert between time zones.
+ >>> new_york = paris.astimezone(new_york_tz)
>>> paris == new_york, paris.date() == new_york.date()
(True, False)
>>> paris - new_york, paris.date() - new_york.date()
(datetime.timedelta(0), datetime.timedelta(1))
>>> paris
- datetime.datetime(2012, 3, 3, 1, 30, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
+ datetime.datetime(2012, 3, 3, 1, 30, tzinfo=zoneinfo.ZoneInfo(key='Europe/Paris'))
>>> new_york
- datetime.datetime(2012, 3, 2, 19, 30, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
+ datetime.datetime(2012, 3, 2, 19, 30, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))
As this example shows, the same datetime has a different date, depending on
the time zone in which it is represented. But the real problem is more
@@ -621,14 +633,13 @@ Troubleshooting
will be the current timezone::
>>> from django.utils import timezone
- >>> timezone.activate(pytz.timezone("Asia/Singapore"))
+ >>> timezone.activate(zoneinfo.ZoneInfo("Asia/Singapore"))
# For this example, we set the time zone to Singapore, but here's how
# you would obtain the current time zone in the general case.
>>> current_tz = timezone.get_current_timezone()
- # Again, this is the correct way to convert between time zones with pytz.
- >>> local = current_tz.normalize(paris.astimezone(current_tz))
+ >>> local = paris.astimezone(current_tz)
>>> local
- datetime.datetime(2012, 3, 3, 8, 30, tzinfo=<DstTzInfo 'Asia/Singapore' SGT+8:00:00 STD>)
+ datetime.datetime(2012, 3, 3, 8, 30, tzinfo=zoneinfo.ZoneInfo(key='Asia/Singapore'))
>>> local.date()
datetime.date(2012, 3, 3)
@@ -645,18 +656,14 @@ Usage
``"Europe/Helsinki"`` **time zone. How do I turn that into an aware
datetime?**
- This is exactly what pytz_ is for.
+ Here you need to create the required ``ZoneInfo`` instance and attach it to
+ the naïve datetime::
+ >>> import zoneinfo
>>> from django.utils.dateparse import parse_datetime
>>> naive = parse_datetime("2012-02-21 10:28:45")
- >>> import pytz
- >>> pytz.timezone("Europe/Helsinki").localize(naive, is_dst=None)
- datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)
-
- Note that ``localize`` is a pytz extension to the :class:`~datetime.tzinfo`
- API. Also, you may want to catch ``pytz.InvalidTimeError``. The
- documentation of pytz contains `more examples`_. You should review it
- before attempting to manipulate aware datetimes.
+ >>> naive.replace(tzinfo=zoneinfo.ZoneInfo("Europe/Helsinki"))
+ datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=zoneinfo.ZoneInfo(key='Europe/Helsinki'))
#. **How can I obtain the local time in the current time zone?**
@@ -677,19 +684,14 @@ Usage
>>> from django.utils import timezone
>>> timezone.localtime(timezone.now())
- datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
+ datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=zoneinfo.ZoneInfo(key='Europe/Paris'))
In this example, the current time zone is ``"Europe/Paris"``.
#. **How can I see all available time zones?**
- pytz_ provides helpers_, including a list of current time zones and a list
- of all available time zones -- some of which are only of historical
- interest. :mod:`zoneinfo` also provides similar functionality via
- :func:`zoneinfo.available_timezones`.
+ :func:`zoneinfo.available_timezones` provides the set of all valid keys for
+ IANA time zones available to your system. See the docs for usage
+ considerations.
.. _pytz: http://pytz.sourceforge.net/
-.. _more examples: http://pytz.sourceforge.net/#example-usage
-.. _these issues: http://pytz.sourceforge.net/#problems-with-localtime
-.. _helpers: http://pytz.sourceforge.net/#helpers
-.. _tz database: https://en.wikipedia.org/wiki/Tz_database