Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

To find 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 find the last date of the current week or quarter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading