Search code examples
pythonpandasdatetimetimezonepytz

The zone attribute is specific to pytz's interface; please migrate to a new time zone provider


I need to filter the lines where the date is today and not more than 2 hours ago according to local time (the code needs to be malleable as I travel to different timezones):


from tzlocal import get_localzone
import pandas as pd
import pytz

df['DATA_HORA'] = df.apply(lambda x: datetime.strptime(f'{x["DATA"]} {x["HORA"]}', '%d/%m/%Y %H:%M'), axis=1)
local_tz = get_localzone()
local_tz = pytz.timezone(local_tz.zone)
df_today = df[(df['DATA_HORA'].dt.tz_localize(local_tz) >= (datetime.now(local_tz) - timedelta(hours=2))) & (df['DATA_HORA'].dt.date == datetime.now(local_tz).date())]

I tried to understand how to do it, according to the specific documentation about it:

https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html#getting-a-time-zone-s-name

But I was not successful, how should I proceed to find my local timezone and not receive this warning anymore?


Solution

  • tzlocal.get_localzonealready returns a timezone object, which you can use directly:

    import pandas as pd
    from tzlocal import get_localzone
    
    z = get_localzone()
    
    print(repr(z))
    # _PytzShimTimezone(zoneinfo.ZoneInfo(key='Europe/Berlin'), 'Europe/Berlin')
    
    print(pd.Timestamp("now", tz=z))
    # 2023-02-14 17:54:32.445179+01:00
    

    You can also unwrap it and obtain the string representation in a way that doesn't trigger warnings:

    print(repr(z.unwrap_shim()))
    # zoneinfo.ZoneInfo(key='Europe/Berlin')
    
    print(z.unwrap_shim().key)
    # Europe/Berlin
    

    ...or also like

    from tzlocal import get_localzone_name
    print(get_localzone_name())
    # Europe/Berlin
    

    Note that if you use pandas, you neither need the datetime module nor pytz here.