Python与Django的时区问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python与Django的时区问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2297字,纯文字阅读大概需要4分钟。
内容图文
在编码中牵扯到时间问题的时候,总是容易被时区问题搞混,一直以来,都是反复试验应付过去,今天终于搞清楚了个中缘由,一个心结也得以化解。Python 的时区问题
datetime.today() / datetime.now()
这两个函数获得的是当前的系统时间,但得到的datetime对象中的tzinfo是空的,即使系统中设置了时区。
datetime.utcnow()
这个函数获得当前的utc时间,应该是根据当前系统时间和时区来计算的。
例如系统时间为14:00,时区为 Asia/Shanghai (北京时间),utcnow返回时间为 6:00。同样,得到的对象中的tzinfo 为空。
环境变量 TZ 对以上函数的影响:
当系统中设置了环境变量 TZ 的时候,或者在python中设置了 os.environ[‘TZ’] 的时候,上面的函数获取的时间便是TZ对应时区的时间。其实这里可以认为 TZ 影响的不是这些函数,而是影响的系统时间,这可以从date命令的返回结果看出。datetime.now() 与 date命令返回的结果总是一致的。
Django的时区问题
明白了上面几个python中的函数,django的时区问题看起来就简单了。
在django的setting中,有一个设置是 TIME_ZONE, 来设置程序中使用的时区。
从django的文档中得知,TIME_ZONE的作用就是改变 os.environ[‘TZ’] ,但改变os.environ[‘TZ’] 并不会改变系统环境变量 TZ , 因此,如果 TIME_ZONE 的设置于系统时区设置不一致,则在程序中 datetime.now() 获得的时间就与 date 命令的时间不一致了。
因此,TIME_ZONE 应该设置为程序希望使用的时区。对于一个本地的程序,TIME_ZONE 设置为与系统时区一样即可;而对于一个国际化的应用,TIME_ZONE 最好设置为UTC,在显示的时候再根据当前用户所在的时区做调整。
手册
classmethod datetime.now([tz])
Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).
Else tz must be an instance of a class tzinfo subclass, and the current date and time are converted to tz‘s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(), utcnow().
classmethod datetime.utcnow()
Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naivedatetime object. See also now().
时区转换代码
import pytz .... #dt the datetime var dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
内容总结
以上是互联网集市为您收集整理的Python与Django的时区问题全部内容,希望文章能够帮你解决Python与Django的时区问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。