Get Local Time Zone

It seems like this should be a trivial thing but I cannot find a way to get the local time zone. In my case I expect to get ‘America/New_York’. Which function gets me the local time zone? TIA.

2 Likes

This is not possible with standard library at the moment (will be added to 3.9 though), in the meantime use dateutil see https://dateutil.readthedocs.io/en/stable/tz.html

2 Likes

The datetime.datetime.astimezone method defaults to the local time-zone. You can use this to get the local time-zone name (using datetime.timezone's names)

import datetime

now = datetime.datetime.now()
local_now = now.astimezone()
local_tz = local_now.tzinfo
local_tzname = local_tz.tzname(local_now)
print(local_tzname)
2 Likes

Thanks. That kind of works. Although I only get the legacy 3 character designation I can live with it.

1 Like

To be clear, this will not be added in Python 3.9.

There’s no generic, cross-platform way to get this information because not all systems use IANA zone keys to configure their time zone. Even the ones that are likely to be configured that way tend to have other mechanisms for configuration.

There are a few ways of making a best guess estimation that would be likely to be right, but I have not spent enough time with trying to detect current local time as an IANA time zone key to be confident in any method I would suggest (for example /etc/localtime is usually a symlink to the right file, but I’m not sure if there’s a good way to separate out the “location on disk” from “IANA key” portions of that link).

2 Likes

I think most people use tzlocal for this.

2 Likes

I do not recommend tzlocal because it is tightly integrated with pytz, which I believe people should move away from.

As far as I know, to the extent that it is possible to accurately get the IANA zone from the system configuration, tzlocal isn’t wildly inaccurate. I am considering adding similar functionality to zoneinfo (though mainly just the “get an IANA zone if it applies” part — not the thing where it falls back to a “local” zone).

3 Likes

@pganssle I opened an issue about that a few hours ago https://github.com/regebro/tzlocal/issues/90

Also just linked your blog post. Great read :slightly_smiling_face:

3 Likes

pip install tzlocal

import tzlocal
print(tzlocal.get_localzone_name())
Asia/Calcutta

In Windows, the time zone name that’s available via the standard library is a localized name, not a standard time zone name or abbreviated identifier. For example, if the UI language is Spanish, then “America/New_York” will be either “Hora estándar del Este” (i.e. “Eastern Standard Time”) or “Hora de verano del Este” (i.e. “Eastern Daylight Time”). This applies to time.tzname, time.strftime('%Z'), and datetime.datetime.now().astimezone().tzname().