<commit_before>==========
Time zones
==========

.. _time-zones-overview:

Overview
========

When support for time zones is enabled, Django stores datetime information in
UTC in the database, uses time-zone-aware datetime objects internally, and
translates them to the end user's time zone in templates and forms.

This is handy if your users live in more than one time zone and you want to
display datetime information according to each user's wall clock.

Even if your website is available in only one time zone, it's still good
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
interacting with end users.

Time zone support is disabled by default. To enable it, set :setting:`USE_TZ =
True <USE_TZ>` in your settings file. Installing pytz_ is highly recommended,
but may not be mandatory depending on your particular database backend,
operating system and time zone. If you encounter an exception querying dates
or times, please try installing it before filing a bug. It's as simple as:

.. code-block:: console

    $ pip install pytz

.. note::

    The default :file:`settings.py` file created by :djadmin:`django-admin
    startproject <startproject>` includes :setting:`USE_TZ = True <USE_TZ>`
    for convenience.

.. note::

    There is also an independent but related :setting:`USE_L10N` setting that
    controls whether Django should activate format localization. See
    :doc:`/topics/i18n/formatting` for more details.

If you're wrestling with a particular problem, start with the :ref:`time zone
FAQ <time-zones-faq>`.

Concepts
========

.. _naive_vs_aware_datetimes:

Naive and aware datetime objects
--------------------------------

Python's :class:`datetime.datetime` objects have a ``tzinfo`` attribute that
can be used to store time zone information, represented as an instance of a
subclass of :class:`datetime.tzinfo`. When this attribute is set and describes
an offset, a datetime object is **aware**. Otherwise, it's **naive**.

You can use :func:`~django.utils.timezone.is_aware` and
:func:`~django.utils.timezone.is_naive` to determine whether datetimes are
aware or naive.

When time zone support is disabled, Django uses naive datetime objects in local
time. This is simple and sufficient for many use cases. In this mode, to obtain
the current time, you would write::

    import datetime

    now = datetime.datetime.now()

When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses
time-zone-aware datetime objects. If your code creates datetime objects, they
should be aware too. In this mode, the example above becomes::

    from django.utils import timezone

    now = timezone.now()

.. warning::

    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.

.. note::

    Python's :class:`datetime.time` objects also feature a ``tzinfo``
    attribute, and PostgreSQL has a matching ``time with time zone`` type.
    However, as PostgreSQL's docs put it, this type "exhibits properties which
    lead to questionable usefulness".

    Django only supports naive time objects and will raise an exception if you
    attempt to save an aware time object, as a timezone for a time with no
    associated date does not make sense.

.. _naive-datetime-objects:

Interpretation of naive datetime objects
----------------------------------------

When :setting:`USE_TZ` is ``True``, Django still accepts naive datetime
objects, in order to preserve backwards-compatibility. When the database layer
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. Other
:class:`~datetime.tzinfo` implementations, such as the local time zone used as
a fallback when pytz_ isn't installed, may raise an exception or return
inaccurate results. That's why you should always create aware datetime objects
when time zone support is enabled.

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
existing ones through :class:`~datetime.timedelta` arithmetic. The only
datetime that's often created in application code is the current time, and
:func:`timezone.now() <django.utils.timezone.now>` automatically does the
right thing.

.. _default-current-time-zone:

Default time zone and current time zone
---------------------------------------

The **default time zone** is the time zone defined by the :setting:`TIME_ZONE`
setting.

The **current time zone** is the time zone that's used for rendering.

You should set the current time zone to the end user's actual time zone with
:func:`~django.utils.timezone.activate`. Otherwise, the default time zone is
used.

.. note::

    As explained in the documentation of :setting:`TIME_ZONE`, Django sets
    environment variables so that its process runs in the default time zone.
    This happens regardless of the value of :setting:`USE_TZ` and of the
    current time zone.

    When :setting:`USE_TZ` is ``True``, this is useful to preserve
    backwards-compatibility with applications that still rely on local time.
    However, :ref:`as explained above <naive-datetime-objects>`, this isn't
    entirely reliable, and you should always work with aware datetimes in UTC
    in your own code. For instance, use
    :meth:`~datetime.datetime.utcfromtimestamp` instead of
    :meth:`~datetime.datetime.fromtimestamp` -- and don't forget to set
    ``tzinfo`` to :data:`~django.utils.timezone.utc`.

Selecting the current time zone<commit_msg>Fixed #26571 -- Corrected recommendation for converting timestamps to tz-aware datetimes.<commit_after>==========
Time zones
==========

.. _time-zones-overview:

Overview
========

When support for time zones is enabled, Django stores datetime information in
UTC in the database, uses time-zone-aware datetime objects internally, and
translates them to the end user's time zone in templates and forms.

This is handy if your users live in more than one time zone and you want to
display datetime information according to each user's wall clock.

Even if your website is available in only one time zone, it's still good
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
interacting with end users.

Time zone support is disabled by default. To enable it, set :setting:`USE_TZ =
True <USE_TZ>` in your settings file. Installing pytz_ is highly recommended,
but may not be mandatory depending on your particular database backend,
operating system and time zone. If you encounter an exception querying dates
or times, please try installing it before filing a bug. It's as simple as:

.. code-block:: console

    $ pip install pytz

.. note::

    The default :file:`settings.py` file created by :djadmin:`django-admin
    startproject <startproject>` includes :setting:`USE_TZ = True <USE_TZ>`
    for convenience.

.. note::

    There is also an independent but related :setting:`USE_L10N` setting that
    controls whether Django should activate format localization. See
    :doc:`/topics/i18n/formatting` for more details.

If you're wrestling with a particular problem, start with the :ref:`time zone
FAQ <time-zones-faq>`.

Concepts
========

.. _naive_vs_aware_datetimes:

Naive and aware datetime objects
--------------------------------

Python's :class:`datetime.datetime` objects have a ``tzinfo`` attribute that
can be used to store time zone information, represented as an instance of a
subclass of :class:`datetime.tzinfo`. When this attribute is set and describes
an offset, a datetime object is **aware**. Otherwise, it's **naive**.

You can use :func:`~django.utils.timezone.is_aware` and
:func:`~django.utils.timezone.is_naive` to determine whether datetimes are
aware or naive.

When time zone support is disabled, Django uses naive datetime objects in local
time. This is simple and sufficient for many use cases. In this mode, to obtain
the current time, you would write::

    import datetime

    now = datetime.datetime.now()

When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses
time-zone-aware datetime objects. If your code creates datetime objects, they
should be aware too. In this mode, the example above becomes::

    from django.utils import timezone

    now = timezone.now()

.. warning::

    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.

.. note::

    Python's :class:`datetime.time` objects also feature a ``tzinfo``
    attribute, and PostgreSQL has a matching ``time with time zone`` type.
    However, as PostgreSQL's docs put it, this type "exhibits properties which
    lead to questionable usefulness".

    Django only supports naive time objects and will raise an exception if you
    attempt to save an aware time object, as a timezone for a time with no
    associated date does not make sense.

.. _naive-datetime-objects:

Interpretation of naive datetime objects
----------------------------------------

When :setting:`USE_TZ` is ``True``, Django still accepts naive datetime
objects, in order to preserve backwards-compatibility. When the database layer
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. Other
:class:`~datetime.tzinfo` implementations, such as the local time zone used as
a fallback when pytz_ isn't installed, may raise an exception or return
inaccurate results. That's why you should always create aware datetime objects
when time zone support is enabled.

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
existing ones through :class:`~datetime.timedelta` arithmetic. The only
datetime that's often created in application code is the current time, and
:func:`timezone.now() <django.utils.timezone.now>` automatically does the
right thing.

.. _default-current-time-zone:

Default time zone and current time zone
---------------------------------------

The **default time zone** is the time zone defined by the :setting:`TIME_ZONE`
setting.

The **current time zone** is the time zone that's used for rendering.

You should set the current time zone to the end user's actual time zone with
:func:`~django.utils.timezone.activate`. Otherwise, the default time zone is
used.

.. note::

    As explained in the documentation of :setting:`TIME_ZONE`, Django sets
    environment variables so that its process runs in the default time zone.
    This happens regardless of the value of :setting:`USE_TZ` and of the
    current time zone.

    When :setting:`USE_TZ` is ``True``, this is useful to preserve
    backwards-compatibility with applications that still rely on local time.
    However, :ref:`as explained above <naive-datetime-objects>`, this isn't
    entirely reliable, and you should always work with aware datetimes in UTC
    in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp`
    and set the ``tz`` parameter to :data:`~django.utils.timezone.utc`.

Selecting the current time zone
{'fraction_non_alphanumeric': 0.08804012345679012, 'fraction_numerical': 0.0010030864197530865, 'mean_word_length': 3.9469465648854962, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2950470', 'n_tokens_mistral': 3435, 'n_tokens_neox': 3235, 'n_words': 1740}