Python:strftime()UTC偏移在Windows中无法按预期工作 [英] Python: strftime() UTC Offset Not working as Expected in Windows
问题描述
我每次使用:
time.strftime("%z")
我得到:
Eastern Daylight Time
但是,我希望使用+ HHMM或-HHMM形式的UTC偏移量.我什至尝试过:
However, I would like the UTC offset in the form +HHMM or -HHMM. I have even tried:
time.strftime("%Z")
哪个仍然会产生:
Eastern Daylight Time
我已经阅读了与strftime()相关的其他几篇文章,%z似乎总是以正确的+ HHMM或-HHMM格式返回UTC偏移量.如何获取strftime()以python 3.3的+ HHMM或-HHMM格式输出?
I have read several other posts related to strftime() and %z always seems to return the UTC offset in the proper +HHMM or -HHMM format. How do I get strftime() to output in the +HHMM or -HHMM format for python 3.3?
我正在运行Windows 7
I'm running Windows 7
推荐答案
For a proper solution, see abarnert’s answer below.
您可以使用 time.altzone
返回一个负偏移量(以秒为单位).例如,我目前正在CEST(UTC + 2)上,所以我得到了这个信息:
You can use time.altzone
which returns a negative offset in seconds. For example, I’m on CEST at the moment (UTC+2), so I get this:
>>> time.altzone
-7200
并以您想要的格式显示它:
And to put it in your desired format:
>>> '{}{:0>2}{:0>2}'.format('-' if time.altzone > 0 else '+', abs(time.altzone) // 3600, abs(time.altzone // 60) % 60)
'+0200'
正如注释中提到的abarnert一样,time.altzone
给出了DST激活时的偏移量,而time.timezone
给出了DST不激活时的偏移量.要弄清楚使用哪个,您可以按照塞巴斯蒂安·J.F.Sebastian在他对另一个问题的答案中的建议 进行操作.这样您就可以像这样获得正确的偏移量:
As abarnert mentioned in the comments, time.altzone
gives the offset when DST is active while time.timezone
does for when DST is not active. To figure out which to use, you can do what J.F. Sebastian suggested in his answer to a different question. So you can get the correct offset like this:
time.altzone if time.daylight and time.localtime().tm_isdst > 0 else time.timezone
正如他所建议的那样,您可以使用 datetime.timezone :
As also suggested by him, you can use the following in Python 3 to get the desired format using datetime.timezone:
>>> datetime.now(timezone.utc).astimezone().strftime('%z')
'+0200'
这篇关于Python:strftime()UTC偏移在Windows中无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!