How can I convert windows timezones to timezones pytz understands?
python, pytz, timezone
Solution
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.
Problem
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> ```