9-bits
9-bits

Reputation: 10775

django localtime

I'm trying to convert utc times to localtime in my template and for some reason doing:

{% load tz %}

{% localtime on %}
{{ value }}
{% endlocaltime %}

still gives me the value in utc

however

{{ value|localtime }} 

gives me the value using my local timezone setting

setting USE_TZ in settings.py to True also seems to do nothing

any idea what i'm doing wrong?

Upvotes: 2

Views: 2857

Answers (3)

Majoris
Majoris

Reputation: 3189

The value of USE_TZ isn’t respected inside of a {% localtime %} block.

Upvotes: 0

Rich Jones
Rich Jones

Reputation: 1432

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!

Upvotes: 0

Dan Hoerst
Dan Hoerst

Reputation: 6328

The {{ value }} date/time object that you are trying to show is a naive datetime object. Naive datetime objects will not convert in template tags - your first example, but will convert in template filters - your 2nd example.

See the first warning here

"Naive" has to do with how the datetime object is created. For info on how to change the date/time object time aware - allowing it to be used in template tags - check out This Thread

Upvotes: 0

Related Questions