Skip to content

Instantly share code, notes, and snippets.

@nitely
Created June 16, 2014 22:12
Show Gist options
  • Save nitely/82e19dd3381886d3a01d to your computer and use it in GitHub Desktop.
Save nitely/82e19dd3381886d3a01d to your computer and use it in GitHub Desktop.
Grouped pytz timezones
"""
Result:
TIMEZONE_CHOICES = [
("Africa", [
("Africa/Abidjan", "Abidjan"),
("Africa/Accra", "Accra"),
#...
]),
("America", [
("America/Argentina/Buenos_Aires", "Argentina, Buenos Aires"),
#...
]),
#...
]
In django:
class User(models.Model):
timezone = models.CharField(_("time zone"), max_length=32, choices=TIMEZONE_CHOICES, default='UTC')
html output:
<select id="id_timezone" name="timezone">
<optgroup label="Africa">
<option value="Africa/Abidjan">Abidjan</option>
<option value="Africa/Accra">Accra</option>
...
"""
import pytz
TIMEZONE_CHOICES = []
def _populate_timezone():
timezones_tree = {}
for tz in pytz.common_timezones:
zone_parts = tz.split(u"/")
zone = zone_parts[0]
zone_list = timezones_tree.get(zone, [])
if not zone_list:
TIMEZONE_CHOICES.append((zone, zone_list))
if len(zone_parts) > 1:
zone_label = u", ".join(zone_parts[1:]).replace(u"_", u" ")
else:
zone_label = zone
zone_list.append((tz, zone_label))
timezones_tree[zone] = zone_list
_populate_timezone()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment