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
754 views
in Technique[技术] by (71.8m points)

python - Django DateTimeField Stores datetime regardless of the tzinfo

Why django DateTimeFieldrestore tzinfo in datetime to <utc>?

Below is my test code.

Is it normal or wrong.?

If it is normal, what is the reason?

models.py
class Date(models.Model):
  datetime = models.DateTimeField()


settings.py
TIME_ZONE = 'Asia/Seoul'
USE_TZ = True


test.py
from django.utils import timezone

datetime = timezone.localtime(timezone.localtimezone.now())
#now datetime is datetime.datetime(2015, 10, 22, 20, 31, 56, 248000, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

models.Date(datetime=datetime).save()
#If I check datebase, It shows 2015-10-22 11:31:56.248000

model.Date.object.get(..)
#It returns datetime.datetime(2015, 10, 22, 11, 31, 56, 248000, tzinfo=<UTC>)

I expect django stores 2015-10-22 20:31:56.248000 and return datetime.datetime(2015, 10, 22, 20, 31, 56, 248000, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

--------------Edit----------------

I used Sqlite.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Make sure you read Django's timezone documentation. The approach is succinctly stated in the very first sentence:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

So, yes, it is normal that you see the return value from the database in UTC.

As for why, the documentation states:

Even if your Web site is available in only one time zone, it’s still good practice to store data in UTC in your database. The main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen.

It also links to a more detailed description in the pytz documentation.


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

...