Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a daterange of the 2nd Fridays of each month?

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)
like image 423
Ginger Avatar asked Mar 13 '23 14:03

Ginger


2 Answers

You can do this easily by setting freq='WOM-2FRI' ("week of month, second Friday") in pd.date_range. So to get your expected output, you could write:

pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)

The output is:

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='WOM-2FRI')
like image 121
Alex Riley Avatar answered Mar 16 '23 07:03

Alex Riley


try this aproach:

import dateutil as du
import pandas as pd

start=du.parser.parse('2016-01-01')

rr = du.rrule.rrule(du.rrule.MONTHLY,
                    byweekday=du.relativedelta.FR(2),
                    dtstart=start,
                    count=12)

dates = [pd.to_datetime(d) for d in rr]

Output:

In [33]: dates
Out[33]:
[Timestamp('2016-01-08 00:00:00'),
 Timestamp('2016-02-12 00:00:00'),
 Timestamp('2016-03-11 00:00:00'),
 Timestamp('2016-04-08 00:00:00'),
 Timestamp('2016-05-13 00:00:00'),
 Timestamp('2016-06-10 00:00:00'),
 Timestamp('2016-07-08 00:00:00'),
 Timestamp('2016-08-12 00:00:00'),
 Timestamp('2016-09-09 00:00:00'),
 Timestamp('2016-10-14 00:00:00'),
 Timestamp('2016-11-11 00:00:00'),
 Timestamp('2016-12-09 00:00:00')]
like image 33
MaxU - stop WAR against UA Avatar answered Mar 16 '23 06:03

MaxU - stop WAR against UA