python - Django 模板中的时区感知日期时间对象

标签 python django datetime

我无法理解如何在 Django 数据库中使用日期时间对象。

我将 datetime.now() 存储在 DateTimeField 中,但无法以可读的方式显示它。目前它显示 UTC 时间。

我应该使用日期时间字段存储时区,还是应该在查询和模板 View 期间始终将其转换为我的时区?

这太复杂了,我一定是完全错了。

如果是这种情况,我将如何在模板中显示太平洋时区时间?

谢谢。

<tbody>
  {% for session in session_list %}
      <tr></tr><td>{{session.date}}</td><td>{{session.email}}</td><td>{{session.userData}}</td></tr>
  {% endfor %}

</tbody>

最佳答案

*) 您可以使用模板标签启用或禁用感知日期时间对象的转换:

{% load tz %}

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

{% localtime off %}
    {{ value }}
{% endlocaltime %}

*) 在setting.py中,可以配置TIME_ZONEUSE_TZ

以 UTC 时间存储日期时间很好(下面引用 Django 网站):

it’s still good practice to store data in UTC in your database. The 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.

official Django Site 中阅读更多内容

关于python - Django 模板中的时区感知日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124050/

相关文章:

python - Django 用于什么目的?

python - 在 django rest 框架中过滤日期时间范围

postgresql - 将日期和时区与 Postgresql 中的时间戳进行比较

python - 在 jupyter 笔记本中将 matplotlib 与 PyQt5 结合使用

Django UpdateView 禁用某些字段

silverlight 时区转换

python - 无法使用 strptime() 正确解析微秒

python - json.dump python mysql 结果

python - 创建仅限于本地主机连接的套接字

python - 如何解析具有未知属性路径的 JSON?