DateDjango时区中的感知对象

2024-04-26 00:59:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解如何在django数据库中使用datetime对象。在

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

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

这太复杂了,我一定是做错了。在

如果是这样的话,我如何在模板中显示太平洋时区时间?在

谢谢。在

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

</tbody>

Tags: 对象django视图模板数据库datetimesession方式
1条回答
网友
1楼 · 发布于 2024-04-26 00:59:39

*)您可以使用templates标记启用或禁用aware datetime对象的转换:

{% load tz %}

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

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

*)在setting.py中,可以配置TIME_ZONE和{}

以UTC时间存储datetime很好(以下引自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

相关问题 更多 >