python – 配置django的setting.TIME_ZONE会影响datetime.datetime.now()吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 配置django的setting.TIME_ZONE会影响datetime.datetime.now()吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2605字,纯文字阅读大概需要4分钟。
内容图文
文件说:
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(),并在视图中执行以下操作:
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()
视窗:
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的setting.TIME_ZONE会影响datetime.datetime.now()吗?全部内容,希望文章能够帮你解决python – 配置django的setting.TIME_ZONE会影响datetime.datetime.now()吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。