Python:strftime,gmtime 不尊重时区 [英] Python: strftime, gmtime not respecting timezone
问题描述
导入时间打印时间.strftime("%a, %d %b %Y %I:%M %p %Z", time.gmtime())
我住在加利福尼亚.出于某种原因,此代码以 GMT 报告时间,而不是遵守系统时区.我知道 strftime 知道我在太平洋,因为它最后仍然打印PST",但它仍然提前 8 小时.还有人注意到这一点吗?有人知道我的系统或我的代码有什么问题吗?
编辑:在命令行运行 date
给了我正确的日期.此外,我已经在两台不同的计算机(mac 和 linux)上运行了它,它们都提前 8 小时报告.您是否希望在使用 strftime 之前更正时区?
time.gmtime()
返回 UTC 时间.你需要的是 time.localtime()
, 时区感知.此行为在 time
模块文档 中有详细记录.
要将任何 time.time()
样式的时间戳转换为 struct_time
,您可以提供一个参数time.localtime()
:><预><代码>>>>打印时间.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.localtime(10.5))1970 年 1 月 1 日星期四 02:00:10 AM EET
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?
EDIT:
running date
at 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?
time.gmtime()
returns the time in UTC. What you need is time.localtime()
, which is timezone-aware. This behaviour is well-documented in the time
module documentation.
EDIT:
To convert any time.time()
style timestamp to a struct_time
, you can supply an argument to
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
这篇关于Python:strftime,gmtime 不尊重时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!