Previous Page
Next Page

12.3. The pytz Module

The third-party pytz module offers the simplest way to create tzinfo instances, which are used to make time zone-aware instances of classes time and datetime. (pytz is based on the Olson library of time zones, documented at http://www.twinsun.com/tz/tz-link.htm. pytz is available at http://pytz.sourceforge.net/.) The best general way to program around the traps and pitfalls of time zones is to always use the UTC time zone internally, converting to other time zones only for display purposes.

pytz supplies common_timezones, a list of over 400 strings that name the most common time zones you might want to use (mostly of the form continent/city, with some alternatives such as 'UTC' and 'US/Pacific'), and all_timezones, a list of over 500 strings that also supply some synonyms for the time zones. For example, to specify the time zone of Lisbon, Portugal, by Olson library standards, you would normally use the string 'Europe/Lisbon', and that is what you find in common_timezones; however, you may also use 'Portugal', which you find only in all_timezones. pytz also supplies utc and UTC, two names for the same object, a tzinfo instance representing Coordinated Universal Time (UTC).

pytz also supplies two functions.

country_timezones

country_timezones(code)

Returns a list of time zone names corresponding to the country whose two-letter ISO code is code. For example, pytz.country_timezones('US') returns a list of 22 strings, from 'America/New_York' to 'Pacific/Honolulu'.

timezone

timezone(name)

Returns an instance of tzinfo corresponding to the time zone named name.

For example, to display the Honolulu equivalent of midnight, December 31, 2005, in New York:

dt = datetime.datetime(2005,12,31,tzinfo=pytz.timezone('America/New_York'))
print dt.astimezone(pytz.timezone('Pacific/Honolulu'))
# emits 2005-12-30 19:00:00-10:00



Previous Page
Next Page