django 的 timezone.now 不显示正确的时间

标签 django django-timezone

我的服务器位于伦敦。

在我的 settings.py我有:

TIME_ZONE = 'Europe/Moscow'
USE_TZ = True

但是当我执行这个时:

from django.utils import timezone

print timezone.now().hour

代码打印伦敦时间。我做错了什么?

更新:

>> timezone.now()
datetime.datetime(2013, 4, 16, 12, 28, 52, 797923, tzinfo=<UTC>)

有趣... tzinfo = <UTC> .所以也许它打印的不是伦敦时间,而是 UTC 的 +0 时间?不管怎样,有没有办法让 Django 显示莫斯科时间?

另外,当我使用 now = timezone.now() 渲染模板时

{{ now.hour }}打印 12(伦敦时间)

{{ now|date:"G" }}打印 16(莫斯科时间)

最佳答案

参见 "Usage" section of the Django docs 中的问题 #2 .

>>> from django.utils import timezone
>>> timezone.localtime(timezone.now())

由于上面的文档也讨论了最佳实践,包括以下摘录:

How can I obtain the local time in the current time zone?

Well, the first question is, do you really need to?

You should only use local time when you’re interacting with humans, and the template layer provides filters and tags to convert datetimes to the time zone of your choice.

Furthermore, Python knows how to compare aware datetimes, taking into account UTC offsets when necessary. It’s much easier (and possibly faster) to write all your model and view code in UTC. So, in most circumstances, the datetime in UTC returned by django.utils.timezone.now() will be sufficient.

关于django 的 timezone.now 不显示正确的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16037020/

相关文章:

django - 将 F() 与注释一起使用,包括 Django 中的另一个查询表达式

python - Django 2.1-namespace= 在 urls.py 中包含时做什么

python - django-rest-framework:在 ViewSet 更新方法中添加额外的权限

javascript - Django 表单和 javascript 或者其他一些方法可以做到同样的事情

python - 为什么时区感知日期时间在 django 中有 2 次

python - RuntimeWarning : DateTimeField Model. 当时区支持处于事件状态时,日期收到了幼稚的日期时间

sql - 如何查询通过自引用多对多表连接的不同实体组?

mysql - django 中的运行时警告

python - 筛选具有日期时间范围的对象 (00 :00 to 23:59:99) in Django

python - Django/DRF - 更改时区不起作用