django 1.4 timezone.now() 与 datetime.datetime.now() [英] django 1.4 timezone.now() vs datetime.datetime.now()

查看:27
本文介绍了django 1.4 timezone.now() 与 datetime.datetime.now()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对夏令时处理有点困惑

I'm a bit confused by the daylight savings handling

settings.py:

settings.py:

TIME_ZONE = 'Europe/London'
USE_TZ = True

在 django 外壳中:

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.

推荐答案

根据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()

它基于 utc 而不是您的默认时区.您可以通过使用实现相同的价值

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_timezone())
print now.astimezone(timezone.utc)

这篇关于django 1.4 timezone.now() 与 datetime.datetime.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆