Python:strftime,gmtime 不尊重时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4788533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:31:15  来源:igfitidea点击:

Python: strftime, gmtime not respecting timezone

pythontimezone

提问by Shaun Budhram

import time
print time.strftime("%a, %d %b %Y %I:%M %p %Z", time.gmtime())

I live in California. For some reason, this code is reporting the time in GMT, instead of respecting the system time zone. I know that strftime knows I'm in pacific, because it still prints 'PST' at the end, but it's still 8 hours ahead. Is anyone else noticing this? Anyone know what's either wrong with my system or my code?

我居住在加利福尼亚州。出于某种原因,此代码以 GMT 报告时间,而不是遵守系统时区。我知道 strftime 知道我在太平洋,因为它最后仍然打印“PST”,但它仍然提前 8 小时。还有人注意到这一点吗?有人知道我的系统或我的代码有什么问题吗?

EDIT: running dateat the command line gives me the correct date. Additionally, I've run this on two different computers (mac and linux) and they both report 8 hours ahead. Are you expected to correct for timezone before using strftime?

编辑date在命令行上运行给了我正确的日期。此外,我已经在两台不同的计算机(mac 和 linux)上运行了它,它们都提前 8 小时报告。您是否希望在使用 strftime 之前更正时区?

采纳答案by thkala

time.gmtime()returns the time in UTC. What you need is time.localtime(), which istimezone-aware. This behaviour is well-documented in the timemodule documentation.

time.gmtime()返回 UTC 时间。你需要的是time.localtime(),它时区感知的。这种行为在time模块文档中有详细记录

EDIT:

编辑:

To convert any time.time()style timestamp to a struct_time, you can supply an argument to time.localtime():

要将任何time.time()样式时间戳转换为 a struct_time,您可以为 提供一个参数 time.localtime()

>>> print time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.localtime(10.5))
Thu, 01 Jan 1970 02:00:10 AM EET

回答by Landon

To change the timezone on your unix system, do something like this:

要更改 unix 系统上的时区,请执行以下操作:

ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime

Browse around in /usr/share/zoneinfo/to find what you want and alter the command above

浏览/usr/share/zoneinfo/以找到您想要的内容并更改上面的命令