Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

django's timezone.now does not show the right time

My server is located in London.

In my settings.py I have:

TIME_ZONE = 'Europe/Moscow'
USE_TZ = True

But when I execute this:

from django.utils import timezone

print timezone.now().hour

the code prints London's time. What am I doing wrong?

UPDATE:

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

Interesting... tzinfo = <UTC>. So maybe it prints not a London time, but UTC's +0 time? Anyway, is there any way to make Django show Moscow time?

Also when I render template with now = timezone.now()

{{ now.hour }} prints 12 (London time)

{{ now|date:"G" }} prints 16 (Moscow time)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

See question #2 in the "Usage" section of the Django docs.

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

Since the doc above also talks about a best practice, including an excerpt below:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...