Get local timezone in django

后端 未结 9 645
轻奢々
轻奢々 2020-12-04 17:47

I have a mysql DATETIME value that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:

9条回答
  •  孤城傲影
    2020-12-04 18:28

    I've created a simple middleware to handle all of this stuff for you:

    https://github.com/Miserlou/django-easy-timezones

    Simply install it and follow the instructions and you're done!

    1. Install django-easy-timezones

      pip install django-easy-timezones pytz pygeoip
      
    2. Add "easy-timezones" to your INSTALLED_APPS setting like this:

      INSTALLED_APPS = (
      ...
      'easy-timezones',
      )
      
    3. Add EasyTimezoneMiddleware to your MIDDLEWARE_CLASSES

      MIDDLEWARE_CLASSES = (
      ...
      'easy-timezones.middleware.EasyTimezoneMiddleware',
      )
      
    4. Add a path to the MaxMind GeoIP database in your settings file:

      GEOIP_DATABASE = '/path/to/your/geoip/database/GeoIP.dat'
      
    5. Enable localtime in your templates.

      {% load tz %}
          The UTC time is {{ object.date }}
      {% localtime on %}
          The local time is {{ object.date }}
      {% endlocaltime %}
      
    6. Tada!

提交回复
热议问题