I need to get the 2nd Friday of each month in Python.
I have written the function below that demonstrates what I need. However, I am wondering if there is a more elegant way to do it using Pandas' date_range
function and appropriate offsets.
def second_friday_of_month_date_range( start, end ):
dr = pd.date_range( start, end, freq='MS' )
first_weekday_of_month_to_2nd_friday_of_month = np.array( [ 12, 11, 10, 9, 8, 14, 13 ], dtype=int )
wd = first_weekday_of_month_to_2nd_friday_of_month[ dr.weekday ]
offsets = [ datetime.timedelta( days=int(x)-1 ) for x in wd ]
dts = [d+o for d, o in zip( dr, offsets)]
return pd.DatetimeIndex( dts )
import pandas as pd
import datetime
d0 = datetime.datetime(2016,1,1)
d1 = datetime.datetime(2017,1,1)
dr = second_friday_of_month_date_range( d0, d1 )
print( dr )
>> DatetimeIndex(['2016-01-08', '2016-02-12', '2016-03-11', '2016-04-08',
'2016-05-13', '2016-06-10', '2016-07-08', '2016-08-12',
'2016-09-09', '2016-10-14', '2016-11-11', '2016-12-09',
'2017-01-13'],
dtype='datetime64[ns]', freq=None, tz=None)