Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get country code for timezone using pytz?

Tags:

python

pytz

I'm using pytz. I've read through the entire documentation sheet, but didn't see how this could be done.

I have a timezone: America/Chicago. All I want is to get the respective country code for this timezone: US.

It shows that I can do the opposite, such as:

>>> country_timezones('ch')
['Europe/Zurich']
>>> country_timezones('CH')
['Europe/Zurich']

but I need to do it the other way around.

Can this be done in Python, using pytz (or any other way for that matter)?

like image 965
Snowman Avatar asked Oct 22 '12 22:10

Snowman


People also ask

How does pytz get time zones?

To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz. utc)'.

What is pytz timezone?

The pytz module allows for date-time conversion and timezone calculations so that your Python applications can keep track of dates and times, while staying accurate to the timezone of a particular location.

Which Python library is used for time zone?

The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.

What is localize in pytz?

The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information): >>> loc_dt = eastern. localize(datetime(2002, 10, 27, 6, 0, 0)) >>> print(loc_dt. strftime(fmt)) 2002-10-27 06:00:00 EST-0500.


1 Answers

You can use the country_timezones object from pytz and generate an inverse mapping:

from pytz import country_timezones

timezone_country = {}
for countrycode in country_timezones:
    timezones = country_timezones[countrycode]
    for timezone in timezones:
        timezone_country[timezone] = countrycode

Now just use the resulting dictionary:

>>> timezone_country['Europe/Zurich']
u'CH'
like image 168
jsalonen Avatar answered Sep 22 '22 11:09

jsalonen