gpt4 book ai didi

python - 时区在 Django 中无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:46 26 4
gpt4 key购买 nike

我想在 Django 中更改时区,所以我阅读了如何操作的文档,这就是我所拥有的:

#settings.py
TIME_ZONE = 'Europe/Ljubljana'

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

给定位置(欧洲/卢 bool 雅那)的 UTC DST 偏移量为 +2,而在我的数据库中我看到了 UTC 时间戳。那我错过了什么?

或者这是否按预期工作,因此它会针对每个请求单独处理(对不同时区的人有用)?但如果是这样,设置 TIME_ZONE = 'Europe/Ljubljana' 有什么用?

最佳答案

来自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.

因此您数据库中的日期时间将始终以 UTC 格式存储,但将在模板和表单中使用正确的 TZ 显示。

要在其他地方以正确的 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>)

关于python - 时区在 Django 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com