Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

django-tz-detect

https://badge.fury.io/py/django-tz-detect.svg https://img.shields.io/pypi/pyversions/django-tz-detect.svg https://img.shields.io/pypi/djversions/django-tz-detect.svg https://github.com/adamcharnock/django-tz-detect/actions/workflows/test.yml/badge.svg

This app will auto-detect a user’s timezone using JavaScript, then configure Django’s timezone localization system accordingly. As a result, dates shown to users will be in their local timezones.

Maintained by Basil Shubin, and some great contributors.

How it works

On the first page view you should find that tz_detect places a piece of asynchronous JavaScript code into your page using the template tag you inserted. The script reads the browser’s timezone name (such as Europe/Amsterdam) using Intl.DateTimeFormat().resolvedOptions().timeZone, along with the UTC offset from getTimezoneOffset, and posts both back to Django.

The timezone name is stored in the user’s session. If the server doesn’t recognise the name, the offset is stored instead, and the middleware picks the closest matching timezone (see TZ_DETECT_COUNTRIES below). On each request, the middleware activates the stored timezone in Django’s timezone support.

The JavaScript will not be displayed in future requests. If the stored timezone becomes unusable, it is dropped from the session and detected again on the next page view.

Once the timezone is stored, the script fires a tzdetect:set event on document, with timezone and offset in event.detail. Use it to update the parts of the first page that show dates and times, for example with htmx:

<div hx-get="/bookings/" hx-trigger="tzdetect:set from:document">
  ...
</div>

with Alpine.js:

<div x-data="{ tz: null }" @tzdetect:set.document="tz = $event.detail.timezone">
  <span x-show="tz">Times are shown in <span x-text="tz"></span></span>
</div>

or with plain JavaScript:

document.addEventListener("tzdetect:set", function (event) {
  console.log("Timezone stored:", event.detail.timezone);
});

Installation

  1. Either checkout tz_detect from GitHub, or install using pip:

    pip install django-tz-detect
  2. Add tz_detect to your INSTALLED_APPS:

    INSTALLED_APPS += (
        'tz_detect',
    )
  3. Be sure you have the django.template.context_processors.request processor

    TEMPLATES = [
        {
            ...
            'OPTIONS': {
                'context_processors': [
                    ...
                    'django.template.context_processors.request',
                ],
            },
        },
    ]
  4. Update your urls.py file:

    urlpatterns += [
        path('tz_detect/', include('tz_detect.urls')),
    ]
  5. Add the detection template tag to your site, ideally in your base layout just before the </body> tag:

    {% load tz_detect %}
    {% tz_detect %}
  6. Add TimezoneMiddleware to MIDDLEWARE:

    MIDDLEWARE += (
        'tz_detect.middleware.TimezoneMiddleware',
    )
  7. (Optional) Configure optional settings

    Set the countries in which your app will be most commonly used:

    # These countries will be prioritized in the search
    # for a matching timezone. Consider putting your
    # app's most popular countries first.
    # Defaults to the top Internet using countries.
    TZ_DETECT_COUNTRIES = ('CN', 'US', 'IN', 'JP', 'BR', 'RU', 'DE', 'FR', 'GB')

    Set the session key that will be used to store the detected timezone

    # Session key to use, defaults to "detected_tz"
    TZ_SESSION_KEY = "my-session-key"

    Reload the page once the timezone is detected, so the first page view is shown in the visitor’s timezone too:

    # Defaults to False
    TZ_DETECT_RELOAD = True

    The page reloads only after the timezone is stored, only on GET requests, and only once, even if the browser keeps rejecting the session cookie. To keep a page from reloading, e.g. while the visitor may already be typing into a form, cancel the event:

    document.addEventListener("tzdetect:set", function (event) {
      event.preventDefault();
    });

Please see example application. This application is used to manually test the functionalities of this package. This also serves as a good example.

Requires Python 3.11+ and Django 5.2+.

Caveats

  • Django’s timezone awareness will not be available on the first page view

  • This method requires JavaScript

  • Timezone detection uses the browser’s timezone setting (its timezone name, or the UTC offset as a fallback), not the user’s location

Future expansion

  • A hook to allow the timezone to be stored against a user

  • Allow timezones to be manually specified

  • Improve timezone detection

  • Optionally using HTML5’s location API for better timezone determination

Contributing

If you’ve found a bug, implemented a feature or customized the template and think it is useful then please consider contributing. Patches, pull requests or just suggestions are welcome!

Credits

django-tz-detect was originally started by Adam Charnock who has now unfortunately abandoned the project.

License

django-tz-detect is released under the MIT license.

Changes

0.7.0 (2026-11-13)

  • Switched packaging from setuptools to hatchling with a src layout.

  • Moved tests out of the package into tests/ and ported them to pytest.

  • Added djLint pre-commit hooks for templates.

  • Added a tzdetect:set event, fired on document once the detected timezone is stored, so pages can refresh dates without a reload, #72.

  • Added the TZ_DETECT_RELOAD setting to reload the page once the timezone is detected, so the first page view is shown in the visitor’s timezone too, #72.

  • Modernized tzdetect.js: it now uses fetch() and dropped support for Internet Explorer. It no longer leaks the areCookiesEnabled global function.

  • Backward incompatible: {% tz_detect %} now renders a plain <script src async> tag that passes its settings in data- attributes, instead of an inline script. The csrf_token, tz_set_endpoint and csrf_header_name globals are gone, and overridden tz_detect/detector.html templates need updating. Pages no longer need 'unsafe-inline' in their Content Security Policy, and attributes given to the tag (such as nonce) now land on that script.

0.6.1 (2026-11-10)

  • Fixed LoginRequiredMiddleware (Django 5.1+) redirecting anonymous visitors’ timezone requests to the login page, #79.

0.6.0 (2026-11-10)

  • Now requires Python 3.11+ and Django 5.2+.

  • Migrated packaging to pyproject.toml, and added pre-commit hooks and GitHub Actions CI/release workflows.

  • Made the session key configurable with the TZ_SESSION_KEY setting, #71.

  • Fixed timezone names containing + (such as Etc/GMT+3) being sent to the server as Etc/GMT 3, #70, #75.

  • Fixed an invalid or unknown timezone in the session raising UnknownTimeZoneError on every request, #70, #76.

  • Replaced pytz with Python’s zoneinfo, and dropped the pytz dependency. On Django 5+, pytz zones shifted every datetime saved through forms by the zone’s LMT offset (e.g. -07:53 instead of -07:00 for America/Los_Angeles), #73, #80.

0.5.0

  • Prefer Intl timezone over offset, #63

0.4.0

  • Support Django 2.2, 3.0, 3.1, 3.2, 4.0

  • Support Python 3.7, 3.8, 3.9, 3.10

  • Drop Python 2 support

  • Switch from Travis CI to GitHub Actions

0.3.0 (2019-11-26)

  • Set attributes on script tag. (Craig Anderson)

0.2.10 (2019-03-30)

  • Dropped support for django < 1.11 (Basil Shubin)

  • Template library load: staticfiles is deprecated in favor of static (Pi Delport)

  • MIDDLEWARE_CLASSES renamed to MIDDLEWARE in Django 1.10 (Craig Anderson)

  • Add Tox configuration (Pi Delport)

  • Simplify offset_to_timezone implementation to use min() (Pi Delport)

  • Update offset_to_timezone to handle edge cases more accurately (Pi Delport)

  • Add tests for all hourly UTC offsets, with known mis-detections (Pi Delport)

0.2.9 (2017-12-18)

  • Excluding testing of django 2.0 on python 2.7 (Adam Charnock)

  • Adding django 2.0 to build matrix (Adam Charnock)

  • Implement handle of settings.CSRF_HEADER_NAME (Roman Gorbil)

  • upgraded test suite (Basil Shubin)

  • Travis config: Add Django 1.11, exclude Python 2.7/Django master (because Django 2.0 will not support Python 2.7), and allow tests against Django master to fail (Drew Hubl)

  • fixed typo, close #31 (Basil Shubin)

0.2.8 (2016-10-21)

  • dropped support for python 2.6 & 3.3 (bashu)

  • make sure example project runs under django 1.10.x (bashu)

  • Update README.rst (bashu)

  • Update .travis.yml (Eric Wang)

  • Add Django 1.10 support (Eric Wang)

0.2.7 (2016-04-28)

  • added missing VERSION file (bashu)

  • Renaming CHANGES -> CHANGES.txt (as required by seed) (bashu)

  • Updating version to be stored in VERSION file (as now done by seed) (bashu)

  • Clean up imports (Filip Figiel)

  • Don’t expect request in templatetag context. Fixes #26 (Filip Figiel)

0.2.6 (2016-02-13)

  • fix for Django 1.10 (kudos to @PetrDlouhy)

  • Added django 1.9 support (Basil Shubin)

0.2.5 (2015-05-06)

  • python 3 support (Basil Shubin)

0.2.4 (2015-05-06)

  • Handle existing sessions storing basestring objects (Basil Shubin)

0.2.3 (2015-05-24)

  • Correctly handle NonExistentTimeError exception. (Basil Shubin)

  • Support django 1.6+ default session serializer, JSONSerializer (Doug Cox)

  • Backward compatibility with django 1.4 (Basil Shubin)

0.2.2 (2013-08-31)

  • Fixing typo in setting name. Thanks to @ustun for noticing. (Adam Charnock)

0.2.1 (2013-08-30)

  • Updating setup.py to use setuptools exclusively (as per recent seed changes) (Adam Charnock)

0.2.0 (2013-08-30)

  • Correcting JS error (for issue #2) (Adam Charnock)

  • Work on issue #2 - Disable posting timezone to server if cookies are disabled (Adam Charnock)

  • Adding badges to readme (Adam Charnock)

0.1.5 (2013-06-26)

  • updating manifest (Adam Charnock)

  • remove offending line (Rich Atkinson)

  • insert new script next to another script, not just inside opening <html> (Rich Atkinson)

0.1.4 (2013-06-19)

  • Fixing setup.py packages directive (Adam Charnock)

0.1.3 (2013-06-19)

  • Fixing setup.py packages directive (Adam Charnock)

0.1.2 (2013-06-19)

  • Fixing setup.py packages directive (Adam Charnock)

0.1.1 (2013-06-19)

  • Fixing setup.py packages directive (Adam Charnock)

0.1.0 (2013-06-19)

  • First version

Metadata

Release files for django-tz-detect 0.7.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

Source distribution for django-tz-detect 0.7.1
File Size Uploaded Provenance Actions
django_tz_detect-0.7.1.tar.gz 17.7 kB With provenance Details for django_tz_detect-0.7.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-tz-detect 0.7.1
File Interpreter ABI Platform Actions
django_tz_detect-0.7.1-py3-none-any.whl Python 3 none any Details for django_tz_detect-0.7.1-py3-none-any.whl

Total release size: 31.9 kB

Release files / django_tz_detect-0.7.1.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL django_tz_detect-0.7.1.tar.gz
Size 17.7 kB
Tags Source
SHA-256 checksum
How to use checksums
4aa2daa11b971ce384c268b3c6ef8b41cc4690f8ff17ecc0328c8c3bcc0ee099
BLAKE2b-256 checksum
How to use checksums
920e4ac59a8b370545769ebb1c58575de9e67d4b19092d46a967fd935025a098
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / django_tz_detect-0.7.1-py3-none-any.whl

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL django_tz_detect-0.7.1-py3-none-any.whl
Size 14.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1cdbabafe39dbb3144cf307e6d9b30360a179deab9ac4ac1a14bdc1d0e8529f9
BLAKE2b-256 checksum
How to use checksums
64d5d0df7ac5ee5912e0a0af41c2429e3aa86026a5ac530981528fa78112a897
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for django-tz-detect 0.7.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Change of provenance

The repository and configuration that created this release differ from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for django_tz_detect-0.7.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page