Python: strftime() UTC Offset Not working as Expected in Windows

后端 未结 4 1360
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 11:44

Every time I use:

time.strftime(\"%z\")

I get:

Eastern Daylight Time

However, I would like the UTC offset

4条回答
  •  萌比男神i
    2020-12-20 12:28

    For a proper solution, see abarnert’s answer below.


    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'
    

    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
    

    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'
    

提交回复
热议问题