gpt4 book ai didi

python - 配置 django settings.TIME_ZONE 会影响 datetime.datetime.now() 吗?

转载 作者:太空狗 更新时间:2023-10-30 02:35:40 24 4
gpt4 key购买 nike

文档说:

http://docs.djangoproject.com/en/dev/ref/settings/#time-zone

Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone setting. Normally, Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in the correct time zone.

我已经阅读了好几遍,但我不清楚 TIME_ZONE 设置是怎么回事。

如果我希望带有日期时间戳的模型显示给用户本地时区,我是否应该管理 UTC 偏移量?

例如,在保存时使用 datetime.datetime.utcnow() 而不是 datetime.datetime.now(),并在 View 中执行如下操作:

display_datetime = model.date_time + datetime.timedelta(USER_UTC_OFFSET)

最佳答案

令我惊讶的是,它确实如此。

web81:~/webapps/dominicrodger2/dominicrodger$ python2.5 manage.py shell
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import settings
>>> settings.TIME_ZONE
'Europe/London'
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2009, 10, 15, 6, 29, 58, 85662)
>>> exit()
web81:~/webapps/dominicrodger2/dominicrodger$ date
Thu Oct 15 00:31:10 CDT 2009

是的,我在写这个答案时确实分心了:-)

我使用 TIME_ZONE 设置,这样我在对象创建时自动添加的时间戳(使用 auto_now_add,我相信它很快就会被弃用)显示时区中的创建时间我设置了。

如果您想将这些时间转换为网站访问者的时区,则需要根据您提供的示例做更多的工作。如果您想进行大量时区转换以在网站访问者的时区中显示时间,那么我强烈建议您将 TIME_ZONE 设置设置为以 UTC 格式存储时间,因为它会让您的从长远来看,生活会更轻松(您可以只使用 UTC 偏移量,而不必担心夏令时)。

如果您有兴趣,我相信时区是根据 TIME_ZONE 设置 here 设置的.

编辑,根据您的评论,它在 Windows 上不起作用,这是因为 Django 源代码中的以下内容:

if hasattr(time, 'tzset'):
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()

window :

C:\Documents and Settings\drodger>python
ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> hasattr(time, 'tzset')
False

Linux:

web81:~$ python2.5
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> hasattr(time, 'tzset')
True

关于python - 配置 django settings.TIME_ZONE 会影响 datetime.datetime.now() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1570339/

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