In a Python project I'm working on, I'd like to be able to get a "human-readable" timezone name of the form America/New_York, corresponding to the system local timezone, to display to the user. Every piece of code I've seen that accesses timezone information only returns either a numeric offset (-0400) or a letter code (EDT) or sometimes both. Is there some Python library that can access this information, or if not that, convert the offset/letter code into a human-readable name?
If there's more than one human-readable name corresponding to a particular timezone, either a list of the possible results or any one of them is fine, and if there is no human-readable name corresponding to the current time zone, I'll take either an exception or None
or []
or whatever.
http://pytz.sourceforge.net/ may be of help. If nothing else, you may be able to grab a list of all of the timezones and then iterate through until you find one that matches your offset.
There is
tzlocal
module that returns apytz
tzinfo object that corresponds to the system local timezone:To answer the question in the title (for people from google), you could use
%Z%z
to print the local time zone info:It prints the current timezone abbreviation and the utc offset corresponding to your local timezone.
The following generates a defaultdict mapping timezone offsets (e.g. '-0400') and abbreviations (e.g. 'EDT') to common geographic timezone names (e.g. 'America/New_York').
Note that timezone abbreviations can have vastly different meanings. For example, 'EST' could stand for Eastern Summer Time (UTC+10) in Australia, or Eastern Standard Time (UTC-5) in North America.
Also, the offsets and abbreviations may change for regions that use daylight standard time. So saving the static dict may not provide the correct timezone name 365 days a year.
If you want only literally what you asked for, "the timezone name of the form America/New_York, corresponding to the system local timezone", and if you only care about Linux (and similar), then this should do the job:
Of course it would be nicer to have a library that encapsulates this in a cleaner way, and that perhaps handles the other cases you mention in comments like already having a
tzinfo
object. I think you can do that with pytz mentioned by Amber but it's not obvious to me just how...This may not have been around when this question was originally written, but here is a snippet to get the time zone official designation:
Further, this can be used with a non-naive datetime object (aka a datetime where the actual timezone has been set using
pytz.<timezone>.localize(<datetime_object>)
ordatetime_object.astimezone(pytz.<timezone>)
as follows:This is, of course, for the edification of those search engine users who landed here. ... See more at the pytz module site.
Check out python-dateutil