Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

django 1.4 timezone.now() vs datetime.datetime.now()

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to timezone.now() source:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...