How to get date of last friday in each quarter?

Viewed 50

I want to find the last friday date in each quater for the given year. For example, the output as follows

last friday in March
last friday in June
last friday in september
last friday in december

How can I find this intelligently based on given year as an input

3 Answers

I'm assuming you don't want the output to be literally

last friday in March
last friday in June
last friday in september
last friday in december

and you just didn't feel like looking up those dates for an example year to include in your question.

Since we know that quarters always end in those months, we can create the last dates of those months. Then, datetime.date.weekday() tells us which day of the week it is. Friday is 4, so we just need to find out how many days we need to go back to achieve this. Then, use datetime.timedelta can subtract that many days, and we should be good to go:

import datetime
def last_fridays_of_quarter(year):
    last_days = [datetime.date(year, 3, 31), datetime.date(year, 6, 30), datetime.date(year, 9, 30), datetime.date(year, 12, 31)]

    for day in last_days:
        days_to_sub = (day.weekday() - 4) % 7
        last_friday = day - datetime.timedelta(days=days_to_sub)
        print(last_friday)

Testing this for 2022:

>>> last_fridays_of_quarter(2022)
2022-03-25
2022-06-24
2022-09-30
2022-12-30

Here's one way to solve it. You store last days of each quarter in a given year in an array. Then you iterate over said quarter ending dates, and calculate the offset that you would need to subtract in order to get to the previous friday.

from datetime import datetime, timedelta

year = 2022
quarter_ending_dates = [
    datetime(year, 3, 31),
    datetime(year, 6, 30),
    datetime(year, 9, 30),
    datetime(year, 12, 31)
]
for ending_date in quarter_ending_dates:
    offset = (ending_date.weekday() - 4) % 7 
    last_friday = ending_date - timedelta(days=offset)
    print(last_friday)

try:

import pandas as pd

def fridays(year):
    df = pd.date_range(start=str(year), end=str(year+1), 
                         freq='W-FRI').strftime('%m/%d/%Y')\
                         .to_frame().reset_index(drop = True)
    
    df.columns = ['date']
    df.index = pd.to_datetime(df['date']).dt.to_period('Q')
    df = df.groupby(df.index).last()
    df.index.name = 'quarter'
    
    return df
fridays(2022)

output is:

quarter date
2022Q1 03/25/2022
2022Q2 06/24/2022
2022Q3 09/30/2022
2022Q4 12/30/2022
Related