django 1.4 timezone.now()vs datetime.datetime.now() [英] django 1.4 timezone.now() vs datetime.datetime.now()
本文介绍了django 1.4 timezone.now()vs datetime.datetime.now()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有点困惑于夏令时处理
settings.py:
TIME_ZONE ='欧洲/伦敦'
USE_TZ = True
在django shell中:
>>>来自django.utils import timezone
>>>> import datetime
>>>> print timezone.now()
2012-05-28 11:19:42.897000 + 00:00
>>> print timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez
one())
2012-05-28 12:20:03.224000 + 01:00
为什么在夏令时不一样?我们已经阅读了文档,但没有一个更聪明的人。
>解决方案
根据 timezone.now()
:
code> def now():
返回一个有意义的或天真的datetime.datetime,具体取决于settings.USE_TZ。
如果设置。 USE_TZ:
#timeit显示datetime.now(tz = utc)慢24%
return datetime.utcnow()。replace(tzinfo = utc)
else:
return datetime.now()
它基于 utc
而不是您的默认时区。您可以通过使用
now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez $ b获得相同的值$ b one())
打印now.astimezone(timezone.utc)
I'm a bit confused by the daylight savings handling
settings.py:
TIME_ZONE = 'Europe/London'
USE_TZ = True
in the django shell:
>>> from django.utils import timezone
>>> import datetime
>>> print timezone.now()
2012-05-28 11:19:42.897000+00:00
>>> print timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez
one())
2012-05-28 12:20:03.224000+01:00
why are they not the same with respect to daylight savings? Both should be locale aware, no?
I've read the docs but am none the wiser.
解决方案
According to timezone.now()
:
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
It's based on utc
instead of your default timezone. You could achieve same value by using
now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez
one())
print now.astimezone(timezone.utc)
这篇关于django 1.4 timezone.now()vs datetime.datetime.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文