简体   繁体   中英

How to set Holidays with Pandas in a timezone-aware way

I have a pandas Dataframe indexed by datetime with hourly frequency (timezone aware):

<class 'pandas.tseries.index.DatetimeIndex'>
[2014-01-01 00:00:00+01:00, ..., 2014-06-30 23:00:00+02:00]
Length: 4933, Freq: None, Timezone: Europe/Rome

I would like to set the weekday to 6 (=Sunday) to all the holidays I set. How can I do it in a timezone aware way?

This might be naive but it works

from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar
from datetime import datetime

class ItalianHolidaysCalendar(AbstractHolidayCalendar):
    rules = [Holiday('Pasquetta', month=4, day=21),
         Holiday('Liberation day', month=4, day=25),
         Holiday('Workers day', month=5, day=1),
         Holiday('Republic day', month=6, day=2)
   ]

cal = ItalianHolidaysCalendar()

holidays_df = pd.DataFrame({})
dd = pd.date_range(datetime(2014,1,1,0), periods=24, freq='H', tz='Europe/Rome')

holidays = cal.holidays(sliceSum.datetime.min().date(), sliceSum.datetime.max().date())
for day in holidays:
    dd = dd.append(pd.date_range(day, day + pd.DateOffset(hours=23), freq='H'))

sliceSum['holiday'] = False
sliceSum.loc[sliceSum.index.isin(dd),['holiday']] = True
sliceSum[sliceSum.holiday].head(50)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM