[Python] pytz library timezone conversion issue

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

  1. Stack

    Stack Membro Participativo

    I am trying to work with django and converting timezones between UTC and my timezone ("America/Winnipeg"), but I keep running into issues and I think there might be a bug. Here is my code:

    #UTC to "America/Winnipeg"
    utc1 = datetime.datetime(2025,4,8,12,00)
    utc1 = utc1.replace(tzinfo = pytz.utc)
    utc2wpg = utc1.astimezone(pytz.timezone("America/Winnipeg"))
    wpgb2utc = utc2wpg.astimezone(pytz.utc)

    print(f"UTC Time: {utc1}")
    print(f"UTC to Winnipeg Time: {utc2wpg}")
    print(f"Winnipeg back to UTC Time: {wpgb2utc}")

    #America/Winnipeg to UTC
    wpg1 = datetime.datetime(2025,4,8,7,0)
    wpg1 = wpg1.replace(tzinfo = pytz.timezone("America/Winnipeg"))
    wpg2utc = wpg1.astimezone(pytz.utc)
    utcb2wpg = wpg2utc.astimezone(pytz.timezone("America/Winnipeg"))

    print(f"Winnipeg Time: {wpg1}")
    print(f"Winnipeg to UTC Time: {wpg2utc}")
    print(f"UTC back to Winnipeg Time: {utcb2wpg}")



    When you run the UTC to "America/Winnipeg" block, you get the output:

    UTC Time: 2025-04-08 12:00:00+00:00
    UTC to Winnipeg Time: 2025-04-08 07:00:00-05:00
    Winnipeg back to UTC Time: 2025-04-08 12:00:00+00:00



    But when you run the exact same timezone converting back from Winnipeg to UTC, you get this output:

    Winnipeg Time: 2025-04-08 07:00:00-06:29
    Winnipeg to UTC Time: 2025-04-08 13:29:00+00:00
    UTC back to Winnipeg Time: 2025-04-08 08:29:00-05:00


    There is clearly a discrepancy in the timezone conversions. Is there an issue with my code or is there an issue with the pytz library's conversion. Are you having the same output?

    I am using Python 3.13

    Continue reading...

Compartilhe esta Página