When working with dates in Python, there are times when you need to calculate specific days, such as the last Saturday of a given month. In this blog, we’ll walk through how to find the date of the last Saturday of any given month using Python.
Let’s break down the task into manageable steps:
- Finding the Last Day of the Month : If the month is December (12), the next month would be January of the next year. For other months, we simply create a date for the first day of the next month and subtract one day to get the last day of the current month.
- Check the day of the week for the last day : The
weekday()
method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. - Calculate the date of the last Saturday : We calculate the difference between the last day of the month and the most recent Saturday. If the last day is already a Saturday,
days_to_saturday
will be zero.
import datetime def get_last_saturday(year, month): # Find the last day of the month if month == 12: last_day = datetime.date(year + 1, 1, 1) - datetime.timedelta(days=1) else: last_day = datetime.date(year, month + 1, 1) - datetime.timedelta(days=1) # Calculate the day of the week for the last day of the month day_of_week = last_day.weekday() # Monday is 0 and Sunday is 6 # Find the last Saturday days_to_saturday = (day_of_week - 5) % 7 last_saturday = last_day - datetime.timedelta(days=days_to_saturday) return last_saturday # Example usage if __name__ == "__main__": year = 2023 month = 6 print(f"The last Saturday of {year}-{month} is {get_last_saturday(year, month)}") month = 7 print(f"The last Saturday of {year}-{month} is {get_last_saturday(year, month)}") month = 12 print(f"The last Saturday of {year}-{month} is {get_last_saturday(year, month)}")
Output:
The last Saturday of 2023-6 is 2023-06-24 The last Saturday of 2023-7 is 2023-07-29 The last Saturday of 2023-12 is 2023-12-30