Is there a list of Pytz Timezones?
You can list all the available timezones with pytz.all_timezones
:
In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]:
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
...]
There is also pytz.common_timezones
:
In [45]: len(pytz.common_timezones)
Out[45]: 403
In [46]: len(pytz.all_timezones)
Out[46]: 563
Python: All possible Timezone Abbreviations for given Timezone Name (and vise versa)
I like unutbu's answer, which led me to the answer that worked for me. I have the locale of the user, so I found that I can use that to remove the ambiguity between time zone abbreviations.
In other words, this fixes the problem with the following:
In [242]: 'Asia/Shanghai' in tzones['CST']
Out[242]: True
In [243]: 'US/Central' in tzones['CST']
Out[243]: True
This function requires a two letter country code:
def GetTimeZoneName(timezone, country_code):
#see if it's already a valid time zone name
if timezone in pytz.all_timezones:
return timezone
#if it's a number value, then use the Etc/GMT code
try:
offset = int(timezone)
if offset > 0:
offset = '+' + str(offset)
else:
offset = str(offset)
return 'Etc/GMT' + offset
except ValueError:
pass
#look up the abbreviation
country_tzones = None
try:
country_tzones = pytz.country_timezones[country_code]
except:
pass
set_zones = set()
if country_tzones is not None and len(country_tzones) > 0:
for name in country_tzones:
tzone = pytz.timezone(name)
for utcoffset, dstoffset, tzabbrev in getattr(tzone, '_transition_info', [[None, None, datetime.datetime.now(tzone).tzname()]]):
if tzabbrev.upper() == timezone.upper():
set_zones.add(name)
if len(set_zones) > 0:
return min(set_zones, key=len)
# none matched, at least pick one in the right country
return min(country_tzones, key=len)
#invalid country, just try to match the timezone abbreviation to any time zone
for name in pytz.all_timezones:
tzone = pytz.timezone(name)
for utcoffset, dstoffset, tzabbrev in getattr(tzone, '_transition_info', [[None, None, datetime.datetime.now(tzone).tzname()]]):
if tzabbrev.upper() == timezone.upper():
set_zones.add(name)
return min(set_zones, key=len)
This returns the correct time zones for CST:
>>> GetTimeZoneName('CST','CN')
'Asia/Shanghai'
>>> GetTimeZoneName('CST','US')
'America/Detroit'
Is there a simplified pytz common_timezone list?
"Useful" is opinionated. Your opinions may not match with others'. For example, the list in your example doesn't have an entry for Arizona - which is not the same as just Mountain Time, as it doesn't have daylight saving time.
The better approach is to offer two dropdowns. The first should list countries, and the second would list time zones within the country. Since many countries only have a single time zone, many users won't need to select time zones at all. Those that do can limit their choice to a much smaller list.
In pytz, you can use the country_timezones
function to get a list of time zones for a particular country.
pytz: getting all timezones, where now is between a specific range of times
The conditional expression used in the if
clause of a list comprehension (that's being used in the answer to the linked question) can be as complex as needed as shown below.
Note I have also modified how the time comparison is done so it no longer ignores the minutes, seconds, and microseconds of the converted value which assumes that the time change difference will always be in whole hours. While that's generally true, there are at least a couple of exceptions I know of (and there could be more in the future).
Also note that the time interval itself is not limited to a whole number of hours — so for instance a time range of begin, end = time(hour=9, minute=0), time(hour=9, minute=30)
could also be checked.
from datetime import datetime, time
from pprint import pprint
import pytz
def datetime_to_time(dt, tz):
"""Convert datetime dt to timezone tz and return its local time of day."""
ndt = dt.astimezone(pytz.timezone(tz))
return time(hour=ndt.hour, minute=ndt.minute, second=ndt.second,
microsecond=ndt.microsecond)
begin, end = time(hour=9), time(hour=10) # Time range.
now = datetime.now(pytz.utc)
in_time_range = [tz for tz in pytz.common_timezones_set if
begin <= datetime_to_time(now, tz) <= end]
print('in_time_range:')
pprint(in_time_range)
How to get the list of US time zones only?
Timezones commonly in use in United States:
import pytz
tznames = pytz.country_timezones['us']
pytz: getting all timezones, where now is specific time
import datetime
import pytz
now = datetime.now(pytz.utc)
# datetime.datetime(2012, 6, 8, 10, 31, 58, 493905, tzinfo=<UTC>)
[tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 9]
# ['Atlantic/Cape_Verde']
[tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 12]
# returns a list of 45 timezones, 'Europe/Oslo' included
Pytz common timezones sorted by offset
I'm not sure that I can understand you correctly but you can try this:
>>> tz = [(item, datetime.datetime.now(pytz.timezone(item)).strftime('%z') + " " + item) for item in pytz.common_timezones]
>>> sorted(tz, key=lambda x: int(x[1].split()[0]))
[('Pacific/Midway', '-1100 Pacific/Midway'), ('Pacific/Niue', '-1100 Pacific/Niue'), ('Pacific/Pago_Pago', '-1100 Pacific/Pago_Pago'), ('Pacific/Honolulu', '-1000 Pacific/Honolulu'), ...
Related Topics
Why Is There No Tuple Comprehension in Python
How to Add Property to a Class Dynamically
How to Lowercase a String in Python
How to Convert String to Datetime Format in Pandas Python
Python Re.Sub Group: Number After \Number
How to Get the Logical Xor of Two Variables in Python
How to Get Attribute of Element from Selenium
Python Strings and Integer Concatenation
"Fire and Forget" Python Async/Await
How to Use a Dll File from Python
Convert Integer to String in Python
Single VS Double Quotes in JSON
Plot a Horizontal Line on a Given Plot