Advertisements
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?
>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