Python Forum

Full Version: Checking if date is holiday in a datetimeindex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everybody!!

I have one column in a dataframe that has a set of dates as pandas.series, like these examples:

1458641 2016-04-22 06:57:41
1458642 2016-01-05 15:56:26
....

And im trying to set if the date is an american holiday, so i tried this:

...

from pandas.tseries.holiday import USFederalHolidayCalendar
cal = USFederalHolidayCalendar()
holidays = pd.to_datetime(cal.holidays(start='2016-01-01', end='2016-06-30'))
completo['IsHoliday'] = pd.to_datetime(completo['pickup_datetime']).dt.date in holidays
print(completo[completo['IsHoliday']==True])
...


But all dates were set as FALSE, even with date '2016-01-01' in the both dataframe column and datettimeindex.

Can Anybody help me!?

Thx,
I am not familiar with pandas (pandas is cool), but if you're iterating over the input line by line, you can parse it. I do it with the python stdlib:

import datetime
from io import StringIO


text = """0 2016-01-01 0000000
1458641 2016-04-22 06:57:41
1458642 2016-01-05 15:56:26"""

like_file = StringIO(text)
# acts as a file, supports also iteration which gives you line by line in a loop

# using your holidays object
for line in like_file:
    _, date, time = line.split()
    date = datetime.datetime.strptime(date, '%Y-%M-%d').date() # this converts the str to a date object
    if date in holidays:
    # here is the magic, the in operator works also with pandas data frames
    # this should also work with a field a column from a pandas data frame
        print(line)
You just need a method to convert your input data to a pandas data frame and do the right job to parse the columns for each row.
For pandas there are many helper functions to make it easier as my example with datetime.
I guess pandas do also have a filter function for this task, that you don't need to iterate like me over the data set by yourself.