我的服务器位于伦敦。
在我的 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/