How to get the last date of the current week or quarter in python?

Question:

I would like to find a simple way to get the last date of the current week or quarter.

To get the last date of the current month I can use the relativdelta function from dateutil:

import pandas as pd 
today_date = pd.Timestamp.today().date() #get today's date

from dateutil.relativedelta import relativedelta
current_month_last_date = today_date + relativedelta(day=31) #get last date of current month

What is an equivalent way to get the last date of the current week or quarter?

Asked By: econlearner

||

Answers:

You can use isocalendar to get week number:

from datetime import date
import calendar

today = date.today()
_, week_number, _ = today.isocalendar()
last_day_of_week = date.fromisocalendar(today.year, week_number, 7)
print(last_day_of_week)

For quarter, you just have to construct the date:

quarter = (today.month-1)//3 + 1
month_of_quarter = quarter*3
last_day_of_quarter = date(today.year, month_of_quarter, calendar.monthrange(today.year, month_of_quarter)[1])
print(last_day_of_quarter)

2023-01-15
2023-03-31
Answered By: NYC Coder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.