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.

1 Like

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

1 Like

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)
1 Like

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).

1 Like

I think most people use tzlocal for this.

1 Like

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).

1 Like

@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:

2 Likes