14

In a windows python environment I can get the local timezone like this, but it's not usable with pytz:

>>> import win32timezone
>>> win32timezone.TimeZoneInfo.local()
TimeZoneInfo(u'US Mountain Standard Time', True)
>>> win32timezone.TimeZoneInfo.local().timeZoneName
u'US Mountain Standard Time'
>>> tz = pytz.timezone(win32timezone.TimeZoneInfo.local().timeZoneName)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\pytz\__init__.py", line 185, in timezone
    raise UnknownTimeZoneError(zone)
pytz.exceptions.UnknownTimeZoneError: 'US Mountain Standard Time'

What's a good way to convert that output to a timezone name pytz.timezone() will understand?


Here's the answer using tzlocal (thanks to Matt):

>>> from tzlocal.win32 import get_localzone_name
>>> get_localzone_name()
'America/Phoenix'
>>> tz = pytz.timezone(get_localzone_name())
>>> tz
<DstTzInfo 'America/Phoenix' MST-1 day, 17:00:00 STD>
Chris Matta
  • 3,263
  • 3
  • 35
  • 48

2 Answers2

14

Don't make any assumptions about what a Windows time zone ID means based on its name. For example US Mountain Standard Time is actually the Windows time zone for the majority of Arizona, which is permanently in MST because it does not implement daylight savings. But the Windows ID for the rest of the mountain time zone is Mountain Standard Time - which does follow daylight savings during Mountain Daylight Time, yet the time zone ID does not change! The only difference between these two zone's IDs is the "US" prefix. In the IANA/Olson database, these are two very distinct zones - America/Phoenix and America/Denver.

What you need are the mappings from Windows to Olson time zone IDs that are provided by the Unicode CLDR project. Read the TimeZone tag wiki for info and links. I am uncertain to if there is already a library that implements this in Python - you may need to do some research, or implement it yourself from the raw data.

UPDATE

A bit of searching, and I found a Python library called tzlocal that has the CLDR mappings. It even is kind enough to include a script that will go fetch the current mappings from the CLDR website and update itself. I haven't tried it myself, but it seems to have the correct approach. It is primarily focused on returning the current system timezone, in an IANA/Olson id that is suitable for use with pytz. Here is the author's blog post describing its usage.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Matt, thanks for pointing that out. This seems like a more complicated problem than I originally thought. It's strange that there's no windows python library that takes all this into account... – Chris Matta Apr 23 '13 at 13:36
  • The Olson database is superior in just about every way, and that's what pytz implements. Is there a reason you have to work with the Windows timezones at all? – Matt Johnson-Pint Apr 23 '13 at 15:08
  • I may have missed it, but is there a way to use pytz to get the Olsen name of the machine's current timezone? – Chris Matta Apr 23 '13 at 16:26
  • @ChrisMatta: the [recent Windows can use Olson database directly](http://www.iana.org/time-zones/repository/tz-link.html). – jfs Sep 13 '14 at 17:10
  • @J.F.Sebastian - Yes, but can Python call into a Windows Runtime API? I'm not sure about that. – Matt Johnson-Pint Sep 13 '14 at 17:27
  • @MattJohnson: I don't know whether you *need* WinRT to get access to tz data. Ideally, you could get the tz data in the tzfile format and feed it to `pytz`. – jfs Sep 13 '14 at 17:49
7

Anurag Uniyal has posted an alternative way to discover timezone names which are consistent with the tzname and utcoffset reported by the computer.


Following up on Matt Johnson's solution, here is how you can load the Unicode Common Locale Data Repository (CLDR) mapping from Windows timezone IDs to Olson timezone names:

import lxml.etree as ET
import collections
import pprint
result = {}
doc = ET.parse('http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml')
for zone in doc.xpath('//mapZone'):
    attrib = zone.attrib
    if attrib['territory'] == '001':
        result[attrib['other']] = attrib['type']
pprint.pprint(dict(result))

yields

{'AUS Central Standard Time': 'Australia/Darwin',
 'AUS Eastern Standard Time': 'Australia/Sydney',
 'Afghanistan Standard Time': 'Asia/Kabul',
 'Alaskan Standard Time': 'America/Anchorage',
 'Arab Standard Time': 'Asia/Riyadh',
 'Arabian Standard Time': 'Asia/Dubai',
 'Arabic Standard Time': 'Asia/Baghdad',
 'Argentina Standard Time': 'America/Buenos_Aires',
 'Atlantic Standard Time': 'America/Halifax',
 'Azerbaijan Standard Time': 'Asia/Baku',
 'Azores Standard Time': 'Atlantic/Azores',
 'Bahia Standard Time': 'America/Bahia',
 'Bangladesh Standard Time': 'Asia/Dhaka',
 'Canada Central Standard Time': 'America/Regina',
 'Cape Verde Standard Time': 'Atlantic/Cape_Verde',
 'Caucasus Standard Time': 'Asia/Yerevan',
 'Cen. Australia Standard Time': 'Australia/Adelaide',
 'Central America Standard Time': 'America/Guatemala',
 'Central Asia Standard Time': 'Asia/Almaty',
 'Central Brazilian Standard Time': 'America/Cuiaba',
 'Central Europe Standard Time': 'Europe/Budapest',
 'Central European Standard Time': 'Europe/Warsaw',
 'Central Pacific Standard Time': 'Pacific/Guadalcanal',
 'Central Standard Time': 'America/Chicago',
 'Central Standard Time (Mexico)': 'America/Mexico_City',
 'China Standard Time': 'Asia/Shanghai',
 'Dateline Standard Time': 'Etc/GMT+12',
 'E. Africa Standard Time': 'Africa/Nairobi',
 'E. Australia Standard Time': 'Australia/Brisbane',
 'E. Europe Standard Time': 'Asia/Nicosia',
 'E. South America Standard Time': 'America/Sao_Paulo',
 'Eastern Standard Time': 'America/New_York',
 'Egypt Standard Time': 'Africa/Cairo',
 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg',
 'FLE Standard Time': 'Europe/Kiev',
 'Fiji Standard Time': 'Pacific/Fiji',
 'GMT Standard Time': 'Europe/London',
 'GTB Standard Time': 'Europe/Bucharest',
 'Georgian Standard Time': 'Asia/Tbilisi',
 'Greenland Standard Time': 'America/Godthab',
 'Greenwich Standard Time': 'Atlantic/Reykjavik',
 'Hawaiian Standard Time': 'Pacific/Honolulu',
 'India Standard Time': 'Asia/Calcutta',
 'Iran Standard Time': 'Asia/Tehran',
 'Israel Standard Time': 'Asia/Jerusalem',
 'Jordan Standard Time': 'Asia/Amman',
 'Kaliningrad Standard Time': 'Europe/Kaliningrad',
 'Korea Standard Time': 'Asia/Seoul',
 'Magadan Standard Time': 'Asia/Magadan',
 'Mauritius Standard Time': 'Indian/Mauritius',
 'Middle East Standard Time': 'Asia/Beirut',
 'Montevideo Standard Time': 'America/Montevideo',
 'Morocco Standard Time': 'Africa/Casablanca',
 'Mountain Standard Time': 'America/Denver',
 'Mountain Standard Time (Mexico)': 'America/Chihuahua',
 'Myanmar Standard Time': 'Asia/Rangoon',
 'N. Central Asia Standard Time': 'Asia/Novosibirsk',
 'Namibia Standard Time': 'Africa/Windhoek',
 'Nepal Standard Time': 'Asia/Katmandu',
 'New Zealand Standard Time': 'Pacific/Auckland',
 'Newfoundland Standard Time': 'America/St_Johns',
 'North Asia East Standard Time': 'Asia/Irkutsk',
 'North Asia Standard Time': 'Asia/Krasnoyarsk',
 'Pacific SA Standard Time': 'America/Santiago',
 'Pacific Standard Time': 'America/Los_Angeles',
 'Pacific Standard Time (Mexico)': 'America/Santa_Isabel',
 'Pakistan Standard Time': 'Asia/Karachi',
 'Paraguay Standard Time': 'America/Asuncion',
 'Romance Standard Time': 'Europe/Paris',
 'Russian Standard Time': 'Europe/Moscow',
 'SA Eastern Standard Time': 'America/Cayenne',
 'SA Pacific Standard Time': 'America/Bogota',
 'SA Western Standard Time': 'America/La_Paz',
 'SE Asia Standard Time': 'Asia/Bangkok',
 'Samoa Standard Time': 'Pacific/Apia',
 'Singapore Standard Time': 'Asia/Singapore',
 'South Africa Standard Time': 'Africa/Johannesburg',
 'Sri Lanka Standard Time': 'Asia/Colombo',
 'Syria Standard Time': 'Asia/Damascus',
 'Taipei Standard Time': 'Asia/Taipei',
 'Tasmania Standard Time': 'Australia/Hobart',
 'Tokyo Standard Time': 'Asia/Tokyo',
 'Tonga Standard Time': 'Pacific/Tongatapu',
 'Turkey Standard Time': 'Europe/Istanbul',
 'US Eastern Standard Time': 'America/Indianapolis',
 'US Mountain Standard Time': 'America/Phoenix',
 'UTC': 'Etc/GMT',
 'UTC+12': 'Etc/GMT-12',
 'UTC-02': 'Etc/GMT+2',
 'UTC-11': 'Etc/GMT+11',
 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar',
 'Venezuela Standard Time': 'America/Caracas',
 'Vladivostok Standard Time': 'Asia/Vladivostok',
 'W. Australia Standard Time': 'Australia/Perth',
 'W. Central Africa Standard Time': 'Africa/Lagos',
 'W. Europe Standard Time': 'Europe/Berlin',
 'West Asia Standard Time': 'Asia/Tashkent',
 'West Pacific Standard Time': 'Pacific/Port_Moresby',
 'Yakutsk Standard Time': 'Asia/Yakutsk'}

If you do not wish your program to depend on lxml or a network connection, you could stick this dict in a module and use it from there.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • interesting technique... I'll run it through some of my common timezones tomorrow and let you know how it works! – Chris Matta Apr 22 '13 at 21:35
  • Close matches are not a good idea when you are talking about IDs of anything. If they were just names, then sure. But the specific IDs of each zone have very particular meanings. See my answer for more details. – Matt Johnson-Pint Apr 22 '13 at 21:50
  • Interesting link in your update. I'm curious though - how does this help with Windows zones? Also, I don't understand what source data they are looking at in that post, they state that they are getting the value from the linux `TZ` variable, but as far as I can tell, that's already an Olson identifier, no? – Matt Johnson-Pint Apr 23 '13 at 15:17
  • @MattJohnson: Uniyal's solution doesn't use the Windows timezone ID, nor the Unix TZ environment variable. To demonstrate its use, he did set TZ to *change* his machine's timezone, but for normal use you would not need to set or even have a TZ environment variable. His solution uses the time module to find the local machine's UTC offsets and tznames -- plural, since `time` provides both a timezone and an altzone for those regions using DST. It then finds all timezones listed in `pytz.all_timezones` which have UTC offsets and tznames which match the local machine's UTC offsets and tznames. – unutbu Apr 23 '13 at 16:10
  • So it's relying on offset match plus abbreviation? That's weird, since Windows won't necessarily give you a valid abbreviation, and abbreviations [can be ambiguous](http://www.timeanddate.com/library/abbreviations/timezones/). It sounds like something similar to [jsTimeZoneDetect](https://bitbucket.org/pellepim/jstimezonedetect) in javascript - but they are clear that it is just a guess. For anything real world, I wouldn't trust anything but the CLDR validated mappings. – Matt Johnson-Pint Apr 23 '13 at 16:14
  • Thanks for posting that. Also, it looks like there is a library that does this already. I just found it, so I can't speak to its reliability, but it looks like it is on track. See my updated answer. And thanks for the dialog! :) – Matt Johnson-Pint Apr 23 '13 at 16:38