I am working with pandas’ tz_localize function to convert dates from local time to UTC:
time_zone = 'America/Santiago'
pd.to_datetime(pd.to_datetime(df['mydate']).apply(lambda x: datetime.strftime(x, '%d-%m-%Y %H:%M:%S'))).dt.tz_localize(time_zone).dt.tz_convert('UTC').dt.tz_localize(None)
This works well, but now I would like to check whether the user-defined time_zone actually exists prior to passing it into tz_localize. I found lists of available countries online, but I do not know how to access this information directly in Python.
I have seen this page about zoneinfo but I am looking for a Python/pandas alternative.
>Solution :
Using the standard library’s zoneinfo and tzdata:
# pip install tzdata # already shipping with pandas
import zoneinfo
all_tz = zoneinfo.available_timezones()
if time_zone in all_tz:
# your code
Alternatively, with pytz (now deprecated):
import pytz
if time_zone in pytz.all_timezones_set:
# your code
If you have python <3.9, you can mimic the zoneinfo.available_timezones function with:
from importlib import resources
with resources.files('tzdata').joinpath('zones').open('r') as f:
all_tz = set(x.strip('\n') for x in f.readlines())
if time_zone in all_tz:
# your code