Megha D S
Megha D S

Reputation: 61

Get timezones of a country

I have a form in which I need the user to choose their timezone. I have a dropdown where one chooses their country and I want to be able to populate the possible timezones for that country as a dropdown for the user to choose.

Eg : The users chooses Mexico and I show the timezones as

'America/Mexico_City',
'America/Cancun',
'America/Merida',
'America/Monterrey',
'America/Matamoros',
'America/Mazatlan',
'America/Chihuahua',
'America/Ojinaga',
'America/Hermosillo',
'America/Tijuana',
'America/Santa_Isabel',
'America/Bahia_Banderas'

and the User will be able to choose one of them for me to process. What is the best way to be able to do this?

I am using Django framework and will be populating the dropdown using js.

Upvotes: 0

Views: 1401

Answers (1)

Bruno A.
Bruno A.

Reputation: 1875

In Python, you can get a map of timezones for each country code using the pytz library:

>>> pytz.country_timezones
<pytz._CountryTimezoneDict at 0x7f0c3c215d68>

To get it as Python dictionary:

>>> dict(pytz.country_timezones)
{'AD': ['Europe/Andorra'],
 'AE': ['Asia/Dubai'],
 'AF': ['Asia/Kabul'],
 'AG': ['America/Antigua'],
 'AI': ['America/Anguilla'],
 'AL': ['Europe/Tirane'],
 'AM': ['Asia/Yerevan'],
 'AO': ['Africa/Luanda'],
 'AQ': ['Antarctica/McMurdo',
  'Antarctica/Casey',
  'Antarctica/Davis',
  'Antarctica/DumontDUrville',
  'Antarctica/Mawson',
  'Antarctica/Palmer',
  'Antarctica/Rothera',
  'Antarctica/Syowa',
  'Antarctica/Troll',
  'Antarctica/Vostok'],
 ...
 'YT': ['Indian/Mayotte'],
 'ZA': ['Africa/Johannesburg'],
 'ZM': ['Africa/Lusaka'],
 'ZW': ['Africa/Harare']}

Then you could JSONify it and add it into your Django template:

timezone_map = dict(pytz.country_timezones)
timezone_json = json.dumps(timezone_map)
# Add timezone_json to your view's template context

On the JS side, you can then read it as follow to populate the drop-down:

let timezoneMap = {{ timezone_json }};
timezoneMap['MX']
// Returns ["America/Mexico_City", "America/Cancun", "America/Merida", "America/Monterrey", "America/Matamoros", "America/Mazatlan", "America/Chihuahua", "America/Ojinaga", "America/Hermosillo", "America/Tijuana", "America/Bahia_Banderas"]

If you want to get this info from your JS and don't mind adding a dependency, I'd say the extension to moment.js for time zone moment-timezone might do what you want, but I've never used it myself.

Upvotes: 1

Related Questions