我无法理解如何在 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_ZONE
和USE_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/