Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test whether timezone exists in Python/pandas?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading