pytz时区标签来调整打印在模板中的日期 [英] pytz timezone tags to adjust date printed in templates

查看:92
本文介绍了pytz时区标签来调整打印在模板中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用普通的datetime对象。在我的模板中:

  {%load tz%} 

{{datetimeobject | timezone:Europe /巴黎}}

{%时区欧洲/巴黎%}
{{datetimeobject}}
{%endtimezone%}

这样打印如下:

 十二月5,2012,4 pm 
2012年12月5日下午3点

所以时区过滤器调整日期,但时区标签不是。



为什么?我如何正确使用标签?我的目标是调整整个模板中的所有datetime对象,而不会在模板中打印的每个datetimeobject中添加过滤器。






编辑



我试图让我的dateobjects时区知道:

  offset = timezone('欧洲/伦敦)
datetimeobj.replace(tzinfo = offset)

但是没有帮助 - 仍然是以前的代码,但是tz感觉datetimeobject是:

  Dec。 5,2012,4 pm 
2012年12月5日下午3点






已解决:我在上面的代码中有一个错误 - 应该是:

  offset = timezone('欧洲/伦敦)
datetimeobj = datetimeobj.replace(tzinfo = offset)


解决方案

你说你使用正常的datetime对象,但它们显然是 timezone naive而不是时区知道



时区过滤器强制将单个值转换为任意时区,而时区标签只需设置当前时区,直到 endtimezone 标签。



您的 datetimeobject 是时区天真,时区过滤器会将其转换为具有默认时区的时区感知datetime,然后将其显示给给过滤器的时区。


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)

解决方案

You say you use "normal datetime objects", but they are apparently 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.

这篇关于pytz时区标签来调整打印在模板中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆