简体   繁体   English

时区在Django中无法正常工作

[英]Timezone not working properly in Django

I want to change timezone in Django, so I read documentation how to do it nad here's what I've got: 我想更改Django中的时区,所以我阅读了文档,该内容如下:

#settings.py
TIME_ZONE = 'Europe/Ljubljana'

#models.py   #date_time gets filled with "auto_now=True")
date_time = models.DateTimeField(auto_now=True)

UTC DST offset for given location (Europe/Ljubljana) is +2, while in my db I see timestamp of UTC. 给定位置(欧洲/卢布尔雅那)的UTC DST偏移为+2,而在我的数据库中,我看到UTC的时间戳。 So what am I missing? 那我想念什么呢?

Or is this working as intended so it gets processed for each request separately (useful for people in different timezones)? 还是按预期方式工作,以便针对每个请求分别进行处理(对不同时区的人有用)? But if this is the case, what's the use of setting TIME_ZONE = 'Europe/Ljubljana' ? 但是,如果是这种情况,设置TIME_ZONE = 'Europe/Ljubljana'什么用?

From the documentation 文档中

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. 启用对时区的支持后,Django会将日期时间信息存储在数据库中的UTC中,在内部使用可识别时区的datetime对象,并将其以模板和形式转换为最终用户的时区。

so the datetime in your DB will always be stored in UTC, but will be displayed using the correct TZ in templates and forms. 因此,数据库中的日期时间将始终存储在UTC中,但会在模板和表单中使用正确的TZ显示。

To get the date in correct TZ elsewhere, use astimezone() : 要获取其他地方的正确TZ日期,请使用astimezone()

>>> from myapp.models import Details
>>> import pytz
>>> d = Details.objects.get(pk=1)
>>> d.added
datetime.datetime(2016, 5, 28, 18, 59, 55, 841193, tzinfo=<UTC>)
>>> localdate = d.added.astimezone(pytz.timezone('Europe/Ljubljana'))
>>> localdate
datetime.datetime(2016, 5, 28, 20, 59, 55, 841193, tzinfo=<DstTzInfo 'Europe/Ljubljana' CEST+2:00:00 DST>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM