django - 不带过滤器的输出时区感知 django 日期时间字段

标签 django postgresql templates timezone

嗨,我升级到 django 1.4,我想利用时区支持,我在 postgres 中保存了一些日期时间字段,一旦我设置了它们,它们就会假设我所在城市的时区保存

USE_TZ = True

并将时区设置为我的城市,我的模板中的日期过滤器标签输出正确的时间(时区)

{{ concert.datetime|date:'f' }}

问题是:我使用日期时间来构建我的 url,如下所示:

{% url event artist_slug=concert.slug_name hour=concert.datetime.hour %}

那些没有正确时区,时间仍然是 UTC,这改变了我的链接,这是我做不到的,它会失去所有的页面排名和很多网站链接使用,是不可行的,不提到 url 的时间与广告时间不同,这看起来很奇怪。 我试过这个:

{% url event artist_slug=concert.slug_name hour=concert.datetime.hour|date:'H' %}

如果不成功,则不会应用日期过滤器标签并引发异常。 我有一个相当大的代码库和很多模板,有没有办法在不使用返回日期时间时区的访问器的情况下解决这个问题?

谢谢。

最佳答案

实际上 Django 文档指出:

Even if your Web site is available in only one time zone, it’s still good practice to store data in UTC in your database. One main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen. (The pytz documentation discusses these issues in greater detail.) This probably doesn’t matter for your blog, but it’s a problem if you over-bill or under-bill your customers by one hour, twice a year, every year. The solution to this problem is to use UTC in the code and use local time only when interacting with end users.

此外:

When time zone support is enabled, Django uses time-zone-aware datetime objects. If your code creates datetime objects, they should be aware too. In this mode, the example above becomes:

import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)

Time zone aware output in templates When you enable time zone support, Django converts aware datetime objects to the current time zone when they’re rendered in templates. This behaves very much like format localization.

最后,没有猴子修补任何东西: https://docs.djangoproject.com/en/1.6/topics/i18n/timezones/#template-tags

关于django - 不带过滤器的输出时区感知 django 日期时间字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199353/

相关文章:

django - 从swift上传照片到django api

python - 我如何反射(reflection) Django 中的属性和模型字段?

postgresql - Amazon Redshift 日期比较

c++ - 也接受模板的模板参数(嵌套模板)

C++ 有函数接受类型 int 和 int[] 使用模板

python - 为 Django 设置 SQLite3 时出现错误配置的数据库错误

python - 如何获得 geodjango 的 k 个最近邻居?

sql - Intellij14 和 "Please Provide Missing Values dialog box"

postgresql - 在 PostgreSQL 中将行转换为列

c++ - 使用可变数量的浮点参数