1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Using Python dateutil, how to judge a timezone string is "valid" or not?

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024 às 04:12.

  1. Stack

    Stack Membro Participativo

    I am using the following code to do the UTC time to local time conversion:

    def UTC_to_local(timezone_str, datetime_UTC):
    """
    convert UTC datetime to local datetime. Input datetime is naive
    """
    try:
    from_zone = dateutil.tz.gettz('UTC')
    to_zone = dateutil.tz.gettz(timezone_str)

    datetime_UTC = datetime_UTC.replace(tzinfo=from_zone)

    # Convert time zone
    datetime_local = datetime_UTC.astimezone(to_zone)

    except Exception as e:
    raise

    return datetime_local


    If I gave the correct timezone_str (e.g., 'America/Chicago'), it works as expected. But even I give the unexpected timezone_str (e.g., 'America/Chicago1' or 'Americaerror/Chicago'), there is still no exception and it just returns different numbers! I think it's more reasonable to get an exception for an unexpected timezone string than just "making the best guess".

    Furthermore, I have found(using IPYTHON):

    In [171]: tz.gettz("America/Chicago")
    Out[171]: tzfile('/usr/share/zoneinfo/America/Chicago')

    In [172]: tz.gettz("America/Chicago1")
    Out[172]: tzstr('America/Chicago1')

    In [173]: tz.gettz("Americaerror/Chicago")
    (None)

    Continue reading...

Compartilhe esta Página