| 1 |
========== |
| 2 |
Time zones |
| 3 |
========== |
| 4 |
|
| 5 |
.. _time-zones-overview: |
| 6 |
|
| 7 |
Overview |
| 8 |
======== |
| 9 |
|
| 10 |
When support for time zones is enabled, Django stores datetime information in |
| 11 |
UTC in the database, uses time-zone-aware datetime objects internally, and |
| 12 |
converts them to the end user's time zone in forms. Templates will use the |
| 13 |
:ref:`default time zone <default-current-time-zone>`, but this can be updated |
| 14 |
to the end user's time zone through the use of :ref:`filters and tags |
| 15 |
<time-zones-in-templates>`. |
| 16 |
|
| 17 |
This is handy if your users live in more than one time zone and you want to |
| 18 |
display datetime information according to each user's wall clock. |
| 19 |
|
| 20 |
Even if your website is available in only one time zone, it's still good |
| 21 |
practice to store data in UTC in your database. The main reason is daylight |
| 22 |
saving time (DST). Many countries have a system of DST, where clocks are moved |
| 23 |
forward in spring and backward in autumn. If you're working in local time, |
| 24 |
you're likely to encounter errors twice a year, when the transitions happen. |
| 25 |
This probably doesn't matter for your blog, but it's a problem if you over bill |
| 26 |
or under bill your customers by one hour, twice a year, every year. The |
| 27 |
solution to this problem is to use UTC in the code and use local time only when |
| 28 |
interacting with end users. |
| 29 |
|
| 30 |
Time zone support is enabled by default. To disable it, set :setting:`USE_TZ = |
| 31 |
False <USE_TZ>` in your settings file. |
| 32 |
|
| 33 |
Time zone support uses :mod:`zoneinfo`, which is part of the Python standard |
| 34 |
library from Python 3.9. |
| 35 |
|
| 36 |
If you're wrestling with a particular problem, start with the :ref:`time zone |
| 37 |
FAQ <time-zones-faq>`. |
| 38 |
|
| 39 |
Concepts |
| 40 |
======== |
| 41 |
|
| 42 |
.. _naive_vs_aware_datetimes: |
| 43 |
|
| 44 |
Naive and aware datetime objects |
| 45 |
-------------------------------- |
| 46 |
|
| 47 |
Python's :class:`datetime.datetime` objects have a ``tzinfo`` attribute that |
| 48 |
can be used to store time zone information, represented as an instance of a |
| 49 |
subclass of :class:`datetime.tzinfo`. When this attribute is set and describes |
| 50 |
an offset, a datetime object is **aware**. Otherwise, it's **naive**. |
| 51 |
|
| 52 |
You can use :func:`~django.utils.timezone.is_aware` and |
| 53 |
:func:`~django.utils.timezone.is_naive` to determine whether datetimes are |
| 54 |
aware or naive. |
| 55 |
|
| 56 |
When time zone support is disabled, Django uses naive datetime objects in local |
| 57 |
time. This is sufficient for many use cases. In this mode, to obtain the |
| 58 |
current time, you would write:: |
| 59 |
|
| 60 |
import datetime |
| 61 |
|
| 62 |
now = datetime.datetime.now() |
| 63 |
|
| 64 |
When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses |
| 65 |
time-zone-aware datetime objects. If your code creates datetime objects, they |
| 66 |
should be aware too. In this mode, the example above becomes:: |
| 67 |
|
| 68 |
from django.utils import timezone |
| 69 |
|
| 70 |
now = timezone.now() |
| 71 |
|
| 72 |
.. warning:: |
| 73 |
|
| 74 |
Dealing with aware datetime objects isn't always intuitive. For instance, |
| 75 |
the ``tzinfo`` argument of the standard datetime constructor doesn't work |
| 76 |
reliably for time zones with DST. Using UTC is generally safe; if you're |
| 77 |
using other time zones, you should review the :mod:`zoneinfo` |
| 78 |
documentation carefully. |
| 79 |
|
| 80 |
.. note:: |
| 81 |
|
| 82 |
Python's :class:`datetime.time` objects also feature a ``tzinfo`` |
| 83 |
attribute, and PostgreSQL has a matching ``time with time zone`` type. |
| 84 |
However, as PostgreSQL's docs put it, this type "exhibits properties which |
| 85 |
lead to questionable usefulness". |
| 86 |
|
| 87 |
Django only supports naive time objects and will raise an exception if you |
| 88 |
attempt to save an aware time object, as a timezone for a time with no |
| 89 |
associated date does not make sense. |
| 90 |
|
| 91 |
.. _naive-datetime-objects: |
| 92 |
|
| 93 |
Interpretation of naive datetime objects |
| 94 |
---------------------------------------- |
| 95 |
|
| 96 |
When :setting:`USE_TZ` is ``True``, Django still accepts naive datetime |
| 97 |
objects, in order to preserve backwards-compatibility. When the database layer |
| 98 |
receives one, it attempts to make it aware by interpreting it in the |
| 99 |
:ref:`default time zone <default-current-time-zone>` and raises a warning. |
| 100 |
|
| 101 |
Unfortunately, during DST transitions, some datetimes don't exist or are |
| 102 |
ambiguous. That's why you should always create aware datetime objects when time |
| 103 |
zone support is enabled. (See the :mod:`Using ZoneInfo section of the zoneinfo |
| 104 |
docs <zoneinfo>` for examples using the ``fold`` attribute to specify the |
| 105 |
offset that should apply to a datetime during a DST transition.) |
| 106 |
|
| 107 |
In practice, this is rarely an issue. Django gives you aware datetime objects |
| 108 |
in the models and forms, and most often, new datetime objects are created from |
| 109 |
existing ones through :class:`~datetime.timedelta` arithmetic. The only |
| 110 |
datetime that's often created in application code is the current time, and |
| 111 |
:func:`timezone.now() <django.utils.timezone.now>` automatically does the |
| 112 |
right thing. |
| 113 |
|
| 114 |
.. _default-current-time-zone: |
| 115 |
|
| 116 |
Default time zone and current time zone |
| 117 |
--------------------------------------- |
| 118 |
|
| 119 |
The **default time zone** is the time zone defined by the :setting:`TIME_ZONE` |
| 120 |
setting. |
| 121 |
|
| 122 |
The **current time zone** is the time zone that's used for rendering. |
| 123 |
|
| 124 |
You should set the current time zone to the end user's actual time zone with |
| 125 |
:func:`~django.utils.timezone.activate`. Otherwise, the default time zone is |
| 126 |
used. |
| 127 |
|
| 128 |
.. note:: |
| 129 |
|
| 130 |
As explained in the documentation of :setting:`TIME_ZONE`, Django sets |
| 131 |
environment variables so that its process runs in the default time zone. |
| 132 |
This happens regardless of the value of :setting:`USE_TZ` and of the |
| 133 |
current time zone. |
| 134 |
|
| 135 |
When :setting:`USE_TZ` is ``True``, this is useful to preserve |
| 136 |
backwards-compatibility with applications that still rely on local time. |
| 137 |
However, :ref:`as explained above <naive-datetime-objects>`, this isn't |
| 138 |
entirely reliable, and you should always work with aware datetimes in UTC |
| 139 |
in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp` |
| 140 |
and set the ``tz`` parameter to :attr:`~datetime.timezone.utc`. |
| 141 |
|
| 142 |
Selecting the current time zone |
| 143 |
------------------------------- |
| 144 |
|
| 145 |
The current time zone is the equivalent of the current :term:`locale <locale |
| 146 |
name>` for translations. However, there's no equivalent of the |
| 147 |
``Accept-Language`` HTTP header that Django could use to determine the user's |
| 148 |
time zone automatically. Instead, Django provides :ref:`time zone selection |
| 149 |
functions <time-zone-selection-functions>`. Use them to build the time zone |
| 150 |
selection logic that makes sense for you. |
| 151 |
|
| 152 |
Most websites that care about time zones ask users in which time zone they live |
| 153 |
and store this information in the user's profile. For anonymous users, they use |
| 154 |
the time zone of their primary audience or UTC. |
| 155 |
:func:`zoneinfo.available_timezones` provides a set of available timezones that |
| 156 |
you can use to build a map from likely locations to time zones. |
| 157 |
|
| 158 |
Here's an example that stores the current timezone in the session. (It skips |
| 159 |
error handling entirely for the sake of simplicity.) |
| 160 |
|
| 161 |
Add the following middleware to :setting:`MIDDLEWARE`:: |
| 162 |
|
| 163 |
import zoneinfo |
| 164 |
|
| 165 |
from django.utils import timezone |
| 166 |
|
| 167 |
|
| 168 |
class TimezoneMiddleware: |
| 169 |
def __init__(self, get_response): |
| 170 |
self.get_response = get_response |
| 171 |
|
| 172 |
def __call__(self, request): |
| 173 |
tzname = request.session.get("django_timezone") |
| 174 |
if tzname: |
| 175 |
timezone.activate(zoneinfo.ZoneInfo(tzname)) |
| 176 |
else: |
| 177 |
timezone.deactivate() |
| 178 |
return self.get_response(request) |
| 179 |
|
| 180 |
Create a view that can set the current timezone:: |
| 181 |
|
| 182 |
from django.shortcuts import redirect, render |
| 183 |
|
| 184 |
# Prepare a map of common locations to timezone choices you wish to offer. |
| 185 |
common_timezones = { |
| 186 |
"London": "Europe/London", |
| 187 |
"Paris": "Europe/Paris", |
| 188 |
"New York": "America/New_York", |
| 189 |
} |
| 190 |
|
| 191 |
|
| 192 |
def set_timezone(request): |
| 193 |
if request.method == "POST": |
| 194 |
request.session["django_timezone"] = request.POST["timezone"] |
| 195 |
return redirect("/") |
| 196 |
else: |
| 197 |
return render(request, "template.html", {"timezones": common_timezones}) |
| 198 |
|
| 199 |
Include a form in ``template.html`` that will ``POST`` to this view: |
| 200 |
|
| 201 |
.. code-block:: html+django |
| 202 |
|
| 203 |
{% load tz %} |
| 204 |
{% get_current_timezone as TIME_ZONE %} |
| 205 |
<form action="{% url 'set_timezone' %}" method="POST"> |
| 206 |
{% csrf_token %} |
| 207 |
<label for="timezone">Time zone:</label> |
| 208 |
<select name="timezone"> |
| 209 |
{% for city, tz in timezones.items %} |
| 210 |
<option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ city }}</option> |
| 211 |
{% endfor %} |
| 212 |
</select> |
| 213 |
<input type="submit" value="Set"> |
| 214 |
</form> |
| 215 |
|
| 216 |
.. _time-zones-in-forms: |
| 217 |
|
| 218 |
Time zone aware input in forms |
| 219 |
============================== |
| 220 |
|
| 221 |
When you enable time zone support, Django interprets datetimes entered in |
| 222 |
forms in the :ref:`current time zone <default-current-time-zone>` and returns |
| 223 |
aware datetime objects in ``cleaned_data``. |
| 224 |
|
| 225 |
Converted datetimes that don't exist or are ambiguous because they fall in a |
| 226 |
DST transition will be reported as invalid values. |
| 227 |
|
| 228 |
.. _time-zones-in-templates: |
| 229 |
|
| 230 |
Time zone aware output in templates |
| 231 |
=================================== |
| 232 |
|
| 233 |
When you enable time zone support, Django converts aware datetime objects to |
| 234 |
the :ref:`current time zone <default-current-time-zone>` when they're rendered |
| 235 |
in templates. This behaves very much like :doc:`format localization |
| 236 |
</topics/i18n/formatting>`. |
| 237 |
|
| 238 |
.. warning:: |
| 239 |
|
| 240 |
Django doesn't convert naive datetime objects, because they could be |
| 241 |
ambiguous, and because your code should never produce naive datetimes when |
| 242 |
time zone support is enabled. However, you can force conversion with the |
| 243 |
template filters described below. |
| 244 |
|
| 245 |
Conversion to local time isn't always appropriate -- you may be generating |
| 246 |
output for computers rather than for humans. The following filters and tags, |
| 247 |
provided by the ``tz`` template tag library, allow you to control the time zone |
| 248 |
conversions. |
| 249 |
|
| 250 |
Template tags |
| 251 |
------------- |
| 252 |
|
| 253 |
.. templatetag:: localtime |
| 254 |
|
| 255 |
``localtime`` |
| 256 |
~~~~~~~~~~~~~ |
| 257 |
|
| 258 |
Enables or disables conversion of aware datetime objects to the current time |
| 259 |
zone in the contained block. |
| 260 |
|
| 261 |
This tag has exactly the same effects as the :setting:`USE_TZ` setting as far |
| 262 |
as the template engine is concerned. It allows a more fine grained control of |
| 263 |
conversion. |
| 264 |
|
| 265 |
To activate or deactivate conversion for a template block, use: |
| 266 |
|
| 267 |
.. code-block:: html+django |
| 268 |
|
| 269 |
{% load tz %} |
| 270 |
|
| 271 |
{% localtime on %} |
| 272 |
{{ value }} |
| 273 |
{% endlocaltime %} |
| 274 |
|
| 275 |
{% localtime off %} |
| 276 |
{{ value }} |
| 277 |
{% endlocaltime %} |
| 278 |
|
| 279 |
.. note:: |
| 280 |
|
| 281 |
The value of :setting:`USE_TZ` isn't respected inside of a |
| 282 |
``{% localtime %}`` block. |
| 283 |
|
| 284 |
.. templatetag:: timezone |
| 285 |
|
| 286 |
``timezone`` |
| 287 |
~~~~~~~~~~~~ |
| 288 |
|
| 289 |
Sets or unsets the current time zone in the contained block. When the current |
| 290 |
time zone is unset, the default time zone applies. |
| 291 |
|
| 292 |
.. code-block:: html+django |
| 293 |
|
| 294 |
{% load tz %} |
| 295 |
|
| 296 |
{% timezone "Europe/Paris" %} |
| 297 |
Paris time: {{ value }} |
| 298 |
{% endtimezone %} |
| 299 |
|
| 300 |
{% timezone None %} |
| 301 |
Server time: {{ value }} |
| 302 |
{% endtimezone %} |
| 303 |
|
| 304 |
.. templatetag:: get_current_timezone |
| 305 |
|
| 306 |
``get_current_timezone`` |
| 307 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 308 |
|
| 309 |
You can get the name of the current time zone using the |
| 310 |
``get_current_timezone`` tag: |
| 311 |
|
| 312 |
.. code-block:: html+django |
| 313 |
|
| 314 |
{% get_current_timezone as TIME_ZONE %} |
| 315 |
|
| 316 |
Alternatively, you can activate the |
| 317 |
:func:`~django.template.context_processors.tz` context processor and |
| 318 |
use the ``TIME_ZONE`` context variable. |
| 319 |
|
| 320 |
Template filters |
| 321 |
---------------- |
| 322 |
|
| 323 |
These filters accept both aware and naive datetimes. For conversion purposes, |
| 324 |
they assume that naive datetimes are in the default time zone. They always |
| 325 |
return aware datetimes. |
| 326 |
|
| 327 |
.. templatefilter:: localtime |
| 328 |
|
| 329 |
``localtime`` |
| 330 |
~~~~~~~~~~~~~ |
| 331 |
|
| 332 |
Forces conversion of a single value to the current time zone. |
| 333 |
|
| 334 |
For example: |
| 335 |
|
| 336 |
.. code-block:: html+django |
| 337 |
|
| 338 |
{% load tz %} |
| 339 |
|
| 340 |
{{ value|localtime }} |
| 341 |
|
| 342 |
.. templatefilter:: utc |
| 343 |
|
| 344 |
``utc`` |
| 345 |
~~~~~~~ |
| 346 |
|
| 347 |
Forces conversion of a single value to UTC. |
| 348 |
|
| 349 |
For example: |
| 350 |
|
| 351 |
.. code-block:: html+django |
| 352 |
|
| 353 |
{% load tz %} |
| 354 |
|
| 355 |
{{ value|utc }} |
| 356 |
|
| 357 |
.. templatefilter:: timezone |
| 358 |
|
| 359 |
``timezone`` |
| 360 |
~~~~~~~~~~~~ |
| 361 |
|
| 362 |
Forces conversion of a single value to an arbitrary timezone. |
| 363 |
|
| 364 |
The argument must be an instance of a :class:`~datetime.tzinfo` subclass or a |
| 365 |
time zone name. |
| 366 |
|
| 367 |
For example: |
| 368 |
|
| 369 |
.. code-block:: html+django |
| 370 |
|
| 371 |
{% load tz %} |
| 372 |
|
| 373 |
{{ value|timezone:"Europe/Paris" }} |
| 374 |
|
| 375 |
.. _time-zones-migration-guide: |
| 376 |
|
| 377 |
Migration guide |
| 378 |
=============== |
| 379 |
|
| 380 |
Here's how to migrate a project that was started before Django supported time |
| 381 |
zones. |
| 382 |
|
| 383 |
Database |
| 384 |
-------- |
| 385 |
|
| 386 |
PostgreSQL |
| 387 |
~~~~~~~~~~ |
| 388 |
|
| 389 |
The PostgreSQL backend stores datetimes as ``timestamp with time zone``. In |
| 390 |
practice, this means it converts datetimes from the connection's time zone to |
| 391 |
UTC on storage, and from UTC to the connection's time zone on retrieval. |
| 392 |
|
| 393 |
As a consequence, if you're using PostgreSQL, you can switch between ``USE_TZ |
| 394 |
= False`` and ``USE_TZ = True`` freely. The database connection's time zone |
| 395 |
will be set to :setting:`DATABASE-TIME_ZONE` or ``UTC`` respectively, so that |
| 396 |
Django obtains correct datetimes in all cases. You don't need to perform any |
| 397 |
data conversions. |
| 398 |
|
| 399 |
.. admonition:: Time zone settings |
| 400 |
|
| 401 |
The :setting:`time zone <DATABASE-TIME_ZONE>` configured for the connection |
| 402 |
in the :setting:`DATABASES` setting is distinct from the general |
| 403 |
:setting:`TIME_ZONE` setting. |
| 404 |
|
| 405 |
Other databases |
| 406 |
~~~~~~~~~~~~~~~ |
| 407 |
|
| 408 |
Other backends store datetimes without time zone information. If you switch |
| 409 |
from ``USE_TZ = False`` to ``USE_TZ = True``, you must convert your data from |
| 410 |
local time to UTC -- which isn't deterministic if your local time has DST. |
| 411 |
|
| 412 |
Code |
| 413 |
---- |
| 414 |
|
| 415 |
The first step is to add :setting:`USE_TZ = True <USE_TZ>` to your settings |
| 416 |
file. At this point, things should mostly work. If you create naive datetime |
| 417 |
objects in your code, Django makes them aware when necessary. |
| 418 |
|
| 419 |
However, these conversions may fail around DST transitions, which means you |
| 420 |
aren't getting the full benefits of time zone support yet. Also, you're likely |
| 421 |
to run into a few problems because it's impossible to compare a naive datetime |
| 422 |
with an aware datetime. Since Django now gives you aware datetimes, you'll get |
| 423 |
exceptions wherever you compare a datetime that comes from a model or a form |
| 424 |
with a naive datetime that you've created in your code. |
| 425 |
|
| 426 |
So the second step is to refactor your code wherever you instantiate datetime |
| 427 |
objects to make them aware. This can be done incrementally. |
| 428 |
:mod:`django.utils.timezone` defines some handy helpers for compatibility |
| 429 |
code: :func:`~django.utils.timezone.now`, |
| 430 |
:func:`~django.utils.timezone.is_aware`, |
| 431 |
:func:`~django.utils.timezone.is_naive`, |
| 432 |
:func:`~django.utils.timezone.make_aware`, and |
| 433 |
:func:`~django.utils.timezone.make_naive`. |
| 434 |
|
| 435 |
Finally, in order to help you locate code that needs upgrading, Django raises |
| 436 |
a warning when you attempt to save a naive datetime to the database: |
| 437 |
|
| 438 |
.. code-block:: pytb |
| 439 |
|
| 440 |
RuntimeWarning: DateTimeField ModelName.field_name received a naive |
| 441 |
datetime (2012-01-01 00:00:00) while time zone support is active. |
| 442 |
|
| 443 |
During development, you can turn such warnings into exceptions and get a |
| 444 |
traceback by adding the following to your settings file:: |
| 445 |
|
| 446 |
import warnings |
| 447 |
|
| 448 |
warnings.filterwarnings( |
| 449 |
"error", |
| 450 |
r"DateTimeField .* received a naive datetime", |
| 451 |
RuntimeWarning, |
| 452 |
r"django\.db\.models\.fields", |
| 453 |
) |
| 454 |
|
| 455 |
Fixtures |
| 456 |
-------- |
| 457 |
|
| 458 |
When serializing an aware datetime, the UTC offset is included, like this:: |
| 459 |
|
| 460 |
"2011-09-01T13:20:30+03:00" |
| 461 |
|
| 462 |
While for a naive datetime, it isn't:: |
| 463 |
|
| 464 |
"2011-09-01T13:20:30" |
| 465 |
|
| 466 |
For models with :class:`~django.db.models.DateTimeField`\ s, this difference |
| 467 |
makes it impossible to write a fixture that works both with and without time |
| 468 |
zone support. |
| 469 |
|
| 470 |
Fixtures generated with ``USE_TZ = False``, or before Django 1.4, use the |
| 471 |
"naive" format. If your project contains such fixtures, after you enable time |
| 472 |
zone support, you'll see :exc:`RuntimeWarning`\ s when you load them. To get |
| 473 |
rid of the warnings, you must convert your fixtures to the "aware" format. |
| 474 |
|
| 475 |
You can regenerate fixtures with :djadmin:`loaddata` then :djadmin:`dumpdata`. |
| 476 |
Or, if they're small enough, you can edit them to add the UTC offset that |
| 477 |
matches your :setting:`TIME_ZONE` to each serialized datetime. |
| 478 |
|
| 479 |
.. _time-zones-faq: |
| 480 |
|
| 481 |
FAQ |
| 482 |
=== |
| 483 |
|
| 484 |
Setup |
| 485 |
----- |
| 486 |
|
| 487 |
#. **I don't need multiple time zones. Should I enable time zone support?** |
| 488 |
|
| 489 |
Yes. When time zone support is enabled, Django uses a more accurate model |
| 490 |
of local time. This shields you from subtle and unreproducible bugs around |
| 491 |
daylight saving time (DST) transitions. |
| 492 |
|
| 493 |
When you enable time zone support, you'll encounter some errors because |
| 494 |
you're using naive datetimes where Django expects aware datetimes. Such |
| 495 |
errors show up when running tests. You'll quickly learn how to avoid invalid |
| 496 |
operations. |
| 497 |
|
| 498 |
On the other hand, bugs caused by the lack of time zone support are much |
| 499 |
harder to prevent, diagnose and fix. Anything that involves scheduled tasks |
| 500 |
or datetime arithmetic is a candidate for subtle bugs that will bite you |
| 501 |
only once or twice a year. |
| 502 |
|
| 503 |
For these reasons, time zone support is enabled by default in new projects, |
| 504 |
and you should keep it unless you have a very good reason not to. |
| 505 |
|
| 506 |
#. **I've enabled time zone support. Am I safe?** |
| 507 |
|
| 508 |
Maybe. You're better protected from DST-related bugs, but you can still |
| 509 |
shoot yourself in the foot by carelessly turning naive datetimes into aware |
| 510 |
datetimes, and vice-versa. |
| 511 |
|
| 512 |
If your application connects to other systems -- for instance, if it queries |
| 513 |
a web service -- make sure datetimes are properly specified. To transmit |
| 514 |
datetimes safely, their representation should include the UTC offset, or |
| 515 |
their values should be in UTC (or both!). |
| 516 |
|
| 517 |
Finally, our calendar system contains interesting edge cases. For example, |
| 518 |
you can't always subtract one year directly from a given date: |
| 519 |
|
| 520 |
.. code-block:: pycon |
| 521 |
|
| 522 |
>>> import datetime |
| 523 |
>>> def one_year_before(value): # Wrong example. |
| 524 |
... return value.replace(year=value.year - 1) |
| 525 |
... |
| 526 |
>>> one_year_before(datetime.datetime(2012, 3, 1, 10, 0)) |
| 527 |
datetime.datetime(2011, 3, 1, 10, 0) |
| 528 |
>>> one_year_before(datetime.datetime(2012, 2, 29, 10, 0)) |
| 529 |
Traceback (most recent call last): |
| 530 |
... |
| 531 |
ValueError: day is out of range for month |
| 532 |
|
| 533 |
To implement such a function correctly, you must decide whether 2012-02-29 |
| 534 |
minus one year is 2011-02-28 or 2011-03-01, which depends on your business |
| 535 |
requirements. |
| 536 |
|
| 537 |
#. **How do I interact with a database that stores datetimes in local time?** |
| 538 |
|
| 539 |
Set the :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` option to the appropriate |
| 540 |
time zone for this database in the :setting:`DATABASES` setting. |
| 541 |
|
| 542 |
This is useful for connecting to a database that doesn't support time zones |
| 543 |
and that isn't managed by Django when :setting:`USE_TZ` is ``True``. |
| 544 |
|
| 545 |
Troubleshooting |
| 546 |
--------------- |
| 547 |
|
| 548 |
#. **My application crashes with** ``TypeError: can't compare offset-naive`` |
| 549 |
``and offset-aware datetimes`` **-- what's wrong?** |
| 550 |
|
| 551 |
Let's reproduce this error by comparing a naive and an aware datetime: |
| 552 |
|
| 553 |
.. code-block:: pycon |
| 554 |
|
| 555 |
>>> from django.utils import timezone |
| 556 |
>>> aware = timezone.now() |
| 557 |
>>> naive = timezone.make_naive(aware) |
| 558 |
>>> naive == aware |
| 559 |
Traceback (most recent call last): |
| 560 |
... |
| 561 |
TypeError: can't compare offset-naive and offset-aware datetimes |
| 562 |
|
| 563 |
If you encounter this error, most likely your code is comparing these two |
| 564 |
things: |
| 565 |
|
| 566 |
- a datetime provided by Django -- for instance, a value read from a form or |
| 567 |
a model field. Since you enabled time zone support, it's aware. |
| 568 |
- a datetime generated by your code, which is naive (or you wouldn't be |
| 569 |
reading this). |
| 570 |
|
| 571 |
Generally, the correct solution is to change your code to use an aware |
| 572 |
datetime instead. |
| 573 |
|
| 574 |
If you're writing a pluggable application that's expected to work |
| 575 |
independently of the value of :setting:`USE_TZ`, you may find |
| 576 |
:func:`django.utils.timezone.now` useful. This function returns the current |
| 577 |
date and time as a naive datetime when ``USE_TZ = False`` and as an aware |
| 578 |
datetime when ``USE_TZ = True``. You can add or subtract |
| 579 |
:class:`datetime.timedelta` as needed. |
| 580 |
|
| 581 |
#. **I see lots of** ``RuntimeWarning: DateTimeField received a naive |
| 582 |
datetime`` ``(YYYY-MM-DD HH:MM:SS)`` ``while time zone support is active`` |
| 583 |
**-- is that bad?** |
| 584 |
|
| 585 |
When time zone support is enabled, the database layer expects to receive |
| 586 |
only aware datetimes from your code. This warning occurs when it receives a |
| 587 |
naive datetime. This indicates that you haven't finished porting your code |
| 588 |
for time zone support. Please refer to the :ref:`migration guide |
| 589 |
<time-zones-migration-guide>` for tips on this process. |
| 590 |
|
| 591 |
In the meantime, for backwards compatibility, the datetime is considered to |
| 592 |
be in the default time zone, which is generally what you expect. |
| 593 |
|
| 594 |
#. ``now.date()`` **is yesterday! (or tomorrow)** |
| 595 |
|
| 596 |
If you've always used naive datetimes, you probably believe that you can |
| 597 |
convert a datetime to a date by calling its :meth:`~datetime.datetime.date` |
| 598 |
method. You also consider that a :class:`~datetime.date` is a lot like a |
| 599 |
:class:`~datetime.datetime`, except that it's less accurate. |
| 600 |
|
| 601 |
None of this is true in a time zone aware environment: |
| 602 |
|
| 603 |
.. code-block:: pycon |
| 604 |
|
| 605 |
>>> import datetime |
| 606 |
>>> import zoneinfo |
| 607 |
>>> paris_tz = zoneinfo.ZoneInfo("Europe/Paris") |
| 608 |
>>> new_york_tz = zoneinfo.ZoneInfo("America/New_York") |
| 609 |
>>> paris = datetime.datetime(2012, 3, 3, 1, 30, tzinfo=paris_tz) |
| 610 |
# This is the correct way to convert between time zones. |
| 611 |
>>> new_york = paris.astimezone(new_york_tz) |
| 612 |
>>> paris == new_york, paris.date() == new_york.date() |
| 613 |
(True, False) |
| 614 |
>>> paris - new_york, paris.date() - new_york.date() |
| 615 |
(datetime.timedelta(0), datetime.timedelta(1)) |
| 616 |
>>> paris |
| 617 |
datetime.datetime(2012, 3, 3, 1, 30, tzinfo=zoneinfo.ZoneInfo(key='Europe/Paris')) |
| 618 |
>>> new_york |
| 619 |
datetime.datetime(2012, 3, 2, 19, 30, tzinfo=zoneinfo.ZoneInfo(key='America/New_York')) |
| 620 |
|
| 621 |
As this example shows, the same datetime has a different date, depending on |
| 622 |
the time zone in which it is represented. But the real problem is more |
| 623 |
fundamental. |
| 624 |
|
| 625 |
A datetime represents a **point in time**. It's absolute: it doesn't depend |
| 626 |
on anything. On the contrary, a date is a **calendaring concept**. It's a |
| 627 |
period of time whose bounds depend on the time zone in which the date is |
| 628 |
considered. As you can see, these two concepts are fundamentally different, |
| 629 |
and converting a datetime to a date isn't a deterministic operation. |
| 630 |
|
| 631 |
What does this mean in practice? |
| 632 |
|
| 633 |
Generally, you should avoid converting a :class:`~datetime.datetime` to |
| 634 |
:class:`~datetime.date`. For instance, you can use the :tfilter:`date` |
| 635 |
template filter to only show the date part of a datetime. This filter will |
| 636 |
convert the datetime into the current time zone before formatting it, |
| 637 |
ensuring the results appear correctly. |
| 638 |
|
| 639 |
If you really need to do the conversion yourself, you must ensure the |
| 640 |
datetime is converted to the appropriate time zone first. Usually, this |
| 641 |
will be the current timezone: |
| 642 |
|
| 643 |
.. code-block:: pycon |
| 644 |
|
| 645 |
>>> from django.utils import timezone |
| 646 |
>>> timezone.activate(zoneinfo.ZoneInfo("Asia/Singapore")) |
| 647 |
# For this example, we set the time zone to Singapore, but here's how |
| 648 |
# you would obtain the current time zone in the general case. |
| 649 |
>>> current_tz = timezone.get_current_timezone() |
| 650 |
>>> local = paris.astimezone(current_tz) |
| 651 |
>>> local |
| 652 |
datetime.datetime(2012, 3, 3, 8, 30, tzinfo=zoneinfo.ZoneInfo(key='Asia/Singapore')) |
| 653 |
>>> local.date() |
| 654 |
datetime.date(2012, 3, 3) |
| 655 |
|
| 656 |
#. **I get an error** "``Are time zone definitions for your database |
| 657 |
installed?``" |
| 658 |
|
| 659 |
If you are using MySQL, see the :ref:`mysql-time-zone-definitions` section |
| 660 |
of the MySQL notes for instructions on loading time zone definitions. |
| 661 |
|
| 662 |
Usage |
| 663 |
----- |
| 664 |
|
| 665 |
#. **I have a string** ``"2012-02-21 10:28:45"`` **and I know it's in the** |
| 666 |
``"Europe/Helsinki"`` **time zone. How do I turn that into an aware |
| 667 |
datetime?** |
| 668 |
|
| 669 |
Here you need to create the required ``ZoneInfo`` instance and attach it to |
| 670 |
the naïve datetime: |
| 671 |
|
| 672 |
.. code-block:: pycon |
| 673 |
|
| 674 |
>>> import zoneinfo |
| 675 |
>>> from django.utils.dateparse import parse_datetime |
| 676 |
>>> naive = parse_datetime("2012-02-21 10:28:45") |
| 677 |
>>> naive.replace(tzinfo=zoneinfo.ZoneInfo("Europe/Helsinki")) |
| 678 |
datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=zoneinfo.ZoneInfo(key='Europe/Helsinki')) |
| 679 |
|
| 680 |
#. **How can I obtain the local time in the current time zone?** |
| 681 |
|
| 682 |
Well, the first question is, do you really need to? |
| 683 |
|
| 684 |
You should only use local time when you're interacting with humans, and the |
| 685 |
template layer provides :ref:`filters and tags <time-zones-in-templates>` |
| 686 |
to convert datetimes to the time zone of your choice. |
| 687 |
|
| 688 |
Furthermore, Python knows how to compare aware datetimes, taking into |
| 689 |
account UTC offsets when necessary. It's much easier (and possibly faster) |
| 690 |
to write all your model and view code in UTC. So, in most circumstances, |
| 691 |
the datetime in UTC returned by :func:`django.utils.timezone.now` will be |
| 692 |
sufficient. |
| 693 |
|
| 694 |
For the sake of completeness, though, if you really want the local time |
| 695 |
in the current time zone, here's how you can obtain it: |
| 696 |
|
| 697 |
.. code-block:: pycon |
| 698 |
|
| 699 |
>>> from django.utils import timezone |
| 700 |
>>> timezone.localtime(timezone.now()) |
| 701 |
datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=zoneinfo.ZoneInfo(key='Europe/Paris')) |
| 702 |
|
| 703 |
In this example, the current time zone is ``"Europe/Paris"``. |
| 704 |
|
| 705 |
#. **How can I see all available time zones?** |
| 706 |
|
| 707 |
:func:`zoneinfo.available_timezones` provides the set of all valid keys for |
| 708 |
IANA time zones available to your system. See the docs for usage |
| 709 |
considerations. |