<p>在2.x中,如果您查看<a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow noreferrer">^{<cd1>}</a>的文档,它们甚至都不会提到</em><code>%z</code>。它根本不能保证存在,更不能保证跨平台的一致性。事实上,正如<a href="https://docs.python.org/2/library/time.html#id2" rel="nofollow noreferrer">footnote 1</a>所暗示的,它由C<code>strftime</code>函数决定。另一方面,在<a href="https://docs.python.org/3/library/time.html#time.strftime" rel="nofollow noreferrer">3.x</a>中,他们确实提到了<code>%z</code>,而且解释它不能以您期望的方式工作的脚注也不容易看到;这就是<a href="http://bugs.python.org/issue20010" rel="nofollow noreferrer">an open bug</a>。</p>
<p>但是,在2.6+(包括所有3.x版本)中,<a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">^{<cd5>}</a><em>保证支持<code>%z</code>作为“格式为+HHMM或-HHMM(如果对象是纯字符串,则为空字符串)的UTC偏移量”。因此,这使得解决方法非常简单:使用<code>datetime</code>,而不是<code>time</code>。确切地说,如何改变取决于你到底想做什么-使用<a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow noreferrer">Python-dateutil</a><code>tz</code>然后<code>datetime.now(tz.tzlocal()).strftime('%z')</code>是获得格式为GMT偏移量的本地时区的方法,但是如果你试图格式化一个完整的时间,则细节会有点不同。</p>
<p>如果您查看源代码,<a href="https://hg.python.org/cpython/file/2.7/Modules/timemodule.c#l391" rel="nofollow noreferrer">^{<cd1>}</a>基本上只是检查格式字符串是否对平台说明符有效,并调用本机<code>strftime</code>函数,而<a href="https://hg.python.org/cpython/file/2.7/Modules/datetimemodule.c#l1154" rel="nofollow noreferrer">^{<cd5>}</a>对不同的说明符有一系列特殊处理,包括<code>%z</code>;特别是,它将在传递内容之前用<code>utcoffset</code>的格式化版本替换<code>%z</code>到<code>strftime</code>。代码自2.7版以来已经更改了几次,甚至彻底地重新组织了一次,但基本上相同的差异甚至在3.5版之前的主干中也存在。</p>