Using Python dateutil, how to judge a timezone string is "valid" or not?
<p>I am using the following code to do the UTC time to local time conversion:</p>

<pre><code>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
</code></pre>

<p>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".</p>

<p>Furthermore, I have found(using IPYTHON):</p>

<pre><code>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)
</code></pre>

<p><strong>Solution #1:</strong> If you can use <a href="https://github.com/newvem/pytz" rel="nofollow">pytz</a></p>

<pre><code>import pytz

if timezone_str in pytz.all_timezones:
    ...
else:
    raise ValueError('Invalid timezone string!')
</code></pre>

<p><strong>Solution #2:</strong></p>

<pre><code>import os
import tarfile
import dateutil.zoneinfo

zi_path = os.path.abspath(os.path.dirname(dateutil.zoneinfo.__file__))
zonesfile = tarfile.TarFile.open(os.path.join(zi_path, 'dateutil-zoneinfo.tar.gz'))
zonenames = zonesfile.getnames()

if timezone_str in zonenames:
    ...
else:
    raise ValueError('Invalid timezone string!')
</code></pre>

python timezone