Skip to main content
 首页 » 编程设计

python time.strftime %z 始终为零而不是时区偏移量

2025年05月04日12cmt

>>> import time 
>>> t=1440935442 
>>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.gmtime(t)) 
'2015/08/30-11:50:42 +0000' 
>>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.localtime(t)) 
'2015/08/30-13:50:42 +0000' 

偏移量保持不变 +0000,但我预计 '2015/08/30-13:50:42 +0200'

时区是正确的,因为命令正在按应有的方式解释大写字母 %Z

>>> time.strftime("%Y/%m/%d-%H:%M:%S %Z",time.localtime(t)) 
'2015/08/30-13:50:42 CEST' 

Unix 日期如我所愿

$ date -u --date @1440935442 +"%Y/%m/%d-%H:%M:%S %z" 
2015/08/30-11:50:42 +0000 
$ date --date @1440935442 +"%Y/%m/%d-%H:%M:%S %z" 
2015/08/30-13:50:42 +0200 

请您参考如下方法:

As documented :

Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.

and :

Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

...

The use of %Z is now deprecated, but the %z escape that expands to the preferred hour/minute offset is not supported by all ANSI C libraries.

time.strftime() 使用 C strftime(),因此行为取决于平台。 %z 应该适用于 POSIX 但 %z may return the same result as %Z on Windows . %z 没有在 Python 2 上记录,因此 time 模块应该返回给定平台上 C strftime() 返回的任何内容,而不做任何更改。

相同的代码在我机器上的 Python 3 中运行:

>>> import time 
>>> t = 1440935442 
>>> time.strftime("%Z%z", time.gmtime(t)) 
'GMT+0000' 
>>> time.strftime("%Z%z", time.localtime(t))  
'CEST+0200' 

您的问题似乎是 Python 2 特有的:

>>> import time 
>>> t = 1440935442 
>>> time.strftime("%Z%z", time.gmtime(t)) 
'CET+0000' 
>>> time.strftime("%Z%z", time.localtime(t)) 
'CEST+0000' 

注意:time.strftime('%Z%z') 在 Python 2 和 3 上返回 'CEST+0200'。差异可能是由于Python <3.3 中缺少 tm_zone、tm_gmtoff 属性。 time.gmtime() 和 time.localtime() 都没有提供 Python 2 的时区信息(tm_isdst 除外,这就是为什么 time .gmtime() 导致CET)。 time.strftime('%Z%z') 使用 C localtime() 因此它可以提供 tm_zone, tm_gmtoff 甚至在 Python 2 上也是如此。

如果您需要可移植的行为并支持过去可能具有不同 tzname、utc 偏移量的时区;您可以使用提供对历史时区数据库的访问的 pytz tzinfo 对象(例如,通过 tzlocal 模块):

>>> from datetime import datetime 
>>> import tzlocal # $ pip install tzlocal 
>>> datetime.fromtimestamp(1440935442, tzlocal.get_localzone()).strftime('%Z%z') 
'CEST+0200'