0

My pandas dataframe "MSYs" has a "start_yr" variable built from a datetime column "Start Date" showing the year of someone's start date (note that month and day of "Start Date" also vary).

start_yr = pd.DatetimeIndex(MSYs['Start Date']).year

I want to use start_yr to help me return a datetime date in another column "Grant Start" showing the third Sunday in August of that variable year. I am stumped.

Hudson H.
  • 15
  • 5

1 Answers1

0

This is an answer to a similar quesion which might help you.

Use the datetime library.

Loop through subset of days in august of that year.

Check if if it is thursday.

Python: third Friday of a month

Here is a solution based on one of the answers in that thread. It is a generalized solution so you should be able to pick a month, a day of the week and the number in the month you want and get that date.

Note: Week days are 0 indexed starting at Monday. So Sunday's index is 6 and monday's index is 0. So when you feed the day_of_week into this function make sure you choose numbers between 0 and 6.

I have defaulted it to choose the 3rd Sunday of the month given the year.

import datetime as dt

def get_year_day(year,month=8,day_of_week=6,num_in_month=3):
    ## set up possible ranges
    range_1 = 7*(num_in_month-1)+1
    range_2 = 7*num_in_month+1
    ## loop through possible range in the year and the month
    for i in range(range_1,range_2):
        date = dt.datetime(year=year,month=month, day=i)
        ## if we have our weekday we can break
        if date.weekday()==day_of_week:
            break
    return date

for i in range(2015,2021):

    print(i,get_year_day(i))

2015 2015-08-16 00:00:00
2016 2016-08-21 00:00:00
2017 2017-08-20 00:00:00
2018 2018-08-19 00:00:00
2019 2019-08-18 00:00:00
2020 2020-08-16 00:00:00

jawsem
  • 751
  • 5
  • 8
  • I'm trying to return a date from a static month and weekday of month, not evaluate a given date. In all other help, date is given; for my example, I'm looking to generate the date. – Hudson H. Feb 02 '20 at 00:32
  • I need to be able to tell the system that I want the third full Sunday in August based on just the year, and return a date. – Hudson H. Feb 02 '20 at 01:14
  • @HudsonH. I have added the solution, based on the thread I linked. Let me know if it works for you. – jawsem Feb 02 '20 at 13:48
  • This does it--brilliant, thank you so much! It also occurred to me to try some magic with date_range, but have yet to explore. – Hudson H. Feb 02 '20 at 15:02