pytz timezone tags to adjust date printed in templates

那年仲夏 提交于 2019-12-10 15:27:14

问题


Inside my app I use normal datetime objects. In my template:

{% load tz %}

{{datetimeobject|timezone:"Europe/Paris"}}

{% timezone "Europe/Paris" %}
{{datetimeobject}}
{% endtimezone %}

This prints something like this:

Dec. 5, 2012, 4 p.m.
Dec. 5, 2012, 3 p.m.

So the timezone filter adjusts the date but timezone tag DOES NOT.

Why is that? And how I can use tag properly? My goal is to adjusts all datetimeobjects in whole template without adding filter to every datetimeobject printed in template.


edit

I tried to make my dateobjects timezone aware:

offset = timezone('Europe/London')
datetimeobj.replace(tzinfo=offset)

But that didnt help - still of the previous code but with tz aware datetimeobject is:

Dec. 5, 2012, 4 p.m.
Dec. 5, 2012, 3 p.m.

solved: I had a mistake in above code - should be:

offset = timezone('Europe/London')
datetimeobj = datetimeobj.replace(tzinfo=offset)

回答1:


You say you use "normal datetime objects", but apparently they are timezone naive instead of timezone aware.

The timezone filter "forces conversion of a single value to an arbitrary timezone" while the timezone tag just sets the current timezone until the endtimezone tag.

Your datetimeobject is timezone naive and the timezone filter will convert it to a timezone aware datetime with the default timezone and then represent it in the timezone given to the filter.



来源:https://stackoverflow.com/questions/14635446/pytz-timezone-tags-to-adjust-date-printed-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!