regebro / tzlocal

A Python module that tries to figure out what your local timezone is

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`get_localzone()` returns different types depending on environment

lloesche opened this issue · comments

I just ran into an issue where on my local machine get_localzone() returns a _PytzShimTimezone() wrapping a ZoneInfo() and providing the unwrap_shim() method, but in an Alpine Docker it returns a datetime.timezone object which does not have that method.

I've now started to write a wrapper along the lines of

def get_local_tzinfo() -> ZoneInfo:
    with warnings.catch_warnings():
        tz = get_localzone()
    if hasattr(tz, "unwrap_shim"):
        tz = tz.unwrap_shim()
    elif isinstance(tz, timezone) and tz == timezone.utc:
        tz = ZoneInfo("Etc/UTC")
    return tz

or thought maybe just

def get_local_tzinfo() -> ZoneInfo:
    zone_name = get_localzone_name()
    if zone_name is None:
        zone_name = "Etc/UTC"
    return ZoneInfo(zone_name)

but felt dirty doing so and am now wondering whether I'm doing something wrong or whether get_localzone() should always return the same type?

What python versions are you running?

I can't see anything in the code that does NOT return the shim, and I don't know how to reproduce this.

I just wanted to follow up on this as I just had the same issue, also on an Alpine image.

The problem seems to come from line 193 in unix.py:

tz = timezone.utc

This returns a datetime.timezone rather than ZoneInfo object.

Note that this appears to be related to #44, and the fix there (following https://wiki.alpinelinux.org/wiki/Setting_the_timezone) fixes the issue, i.e.

apk add tzdata
cp /usr/share/zoneinfo/Etc/UTC /etc/localtime
echo "Etc/UTC > /etc/timezone

However, it would be nice if _get_localzone always returned the same object type, even when the time zone can't be determined.

EDIT: Note that this is on Python 3.8, if it matters.

These are all TzInfo objects, which is the type used for timezones, and the type you should expect any timezone to use, unless you are still using pytz, in which case you need to stay on tzlocal 4.x, and in that case line 193 may indeed be an issue. I'll look at that.

4.3.2 will fix that issue.

Yes, using pytz and tzlocal v4 - many thanks @regebro!