hpet
hpet

Reputation: 27

pandas date_range does not exclude holidays

I have been trying to exclude a set of dates from my pandas bdate_range result but for some reason they keep on appearing.

I was following the notes within here https://pandas.pydata.org/docs/reference/api/pandas.bdate_range.html, ie apply bdate_range and also freq='C' . I thought that my exclude from list has been set up incorrectly, but am not seeing any errors thrown out when the script is run.

Sample code is below. Is anyone able to see what I have done wrong? would prefer the bdate_range to work instead of placing in some sort of workaround

import pandas as pd  
import datetime

exclude = [pd.datetime(2020, 1, 7), pd.datetime(2020, 1, 27)]

pd.bdate_range('2020/1/1','2020/1/31',freq='C',  holidays=exclude, )

Result still includes the 7th and the 27th that I am attempting to exclude out

DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-06',
               '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10',
               '2020-01-13', '2020-01-14', '2020-01-15', '2020-01-16',
               '2020-01-17', '2020-01-20', '2020-01-21', '2020-01-22',
               '2020-01-23', '2020-01-24', '2020-01-27', '2020-01-28',
               '2020-01-29', '2020-01-30', '2020-01-31'],
              dtype='datetime64[ns]', freq='C')

screenshot of result

Have also tried using from datetime as suggested, but same result

using from datetime

Upvotes: 0

Views: 2425

Answers (2)

srdg
srdg

Reputation: 595

Instead of
import datetime
do
from datetime import datetime
and instead of
exclude = [pd.datetime(2020, 1, 7), pd.datetime(2020, 1, 27)]
do
exclude = [datetime(2020, 1, 7), datetime(2020, 1, 27)]

Upvotes: 0

vtasca
vtasca

Reputation: 1760

Are you sure you're executing the same thing you're sharing with us here? I just ran your code and it seems to exclude the dates you mention:

DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-06',
               '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-13',
               '2020-01-14', '2020-01-15', '2020-01-16', '2020-01-17',
               '2020-01-20', '2020-01-21', '2020-01-22', '2020-01-23',
               '2020-01-24', '2020-01-28', '2020-01-29', '2020-01-30',
               '2020-01-31'],
              dtype='datetime64[ns]', freq='C')

In case you get the deprecation warning, don't use pd.datetime but rather import it from its own library, using from datetime import datetime.

Upvotes: 2

Related Questions