[Python] Python time.strftime gives different results for %Z and %z

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm getting some strange behavior when I pass a UTC time struct to python's time.strftime. Using %z seems to always give me my local offset rather than 0:

    >>> import time
    >>> a = time.gmtime()
    >>> a
    time.struct_time(tm_year=2025, tm_mon=4, tm_mday=28, tm_hour=5, tm_min=13, tm_sec=45, tm_wday=0, tm_yday=118, tm_isdst=0)
    >>> a.tm_zone
    'UTC'
    >>> a.tm_gmtoff
    0
    >>> time.strftime("%a, %d %b %Y %I:%M %p %Z", a)
    'Mon, 28 Apr 2025 05:13 AM UTC'
    >>> time.strftime("%a, %d %b %Y %I:%M %p %z", a)
    'Mon, 28 Apr 2025 05:13 AM -0500'


    The variable a is in UTC, so I'd expect %Z to give me UTC (which it does), and %z to give me +0000, but it doesn't. It prints out my local tz offset. And it's not even adjusting the time for that offset (it's still 5:13). And it's not even the right offset, we're in daylight saving time right now, so it should be -0400.

    I'm using Python 3.13.2 installed from homebrew on macos 15.3.2. But I also just checked the system python3 from Apple, which is 3.9.6, and it exhibits the same behavior.

    The command-line date utility seems to always have %Z and %z agree with each other:

    $ date '+%a, %d %b %Y %I:%M %p %Z'
    Mon, 28 Apr 2025 01:39 AM EDT
    $ date '+%a, %d %b %Y %I:%M %p %z'
    Mon, 28 Apr 2025 01:39 AM -0400

    # And using UTC:
    $ TZ=UTC date '+%a, %d %b %Y %I:%M %p %Z'
    Mon, 28 Apr 2025 05:39 AM UTC
    $ TZ=UTC date '+%a, %d %b %Y %I:%M %p %z'
    Mon, 28 Apr 2025 05:39 AM +0000


    Is this known? intentional? documented? I saw some other questions on stackoverflow with similar questions, but none were exactly like what I'm seeing (specifically python time.strftime %z is always zero instead of timezone offset where %z was always giving 0 when they expected a non-zero offset, which is the opposite of what I'm seeing). Is there a way to get time.strftime to always format a time with the timezone of the struct passed to it?

    Continue reading...

Compartilhe esta Página