Wednesday, November 27, 2024
Google search engine
HomeLanguagesGet the Last Saturday of the Month in Python

Get the Last Saturday of the Month in Python

This article will teach you to find the last Saturday of the month in Python. This covers various methods using which we can find the last Saturday of any/current month of any/current year.

Example:

Input: Year = 2022, Month = 11
Output: 26

Input: Year = 2022, Month = 12
Output: 31

Find the last Saturday of the month Using the Calendar Module

This approach uses the calendar module to determine the last Saturday of any given month. Calendar is a built-in module in Python that controls calendar-related operations. The calendar module enables output calendars that resemble programs and provides other advantageous calendar-related features.

The current Gregorian calendar is the idealized calendar utilized by the methods and classes specified in the Calendar module, extended infinitely in both directions. These calendars establish Monday as the first day of the week and Sunday as its last day automatically (the European convention). It can be used to find the last Saturday of any Month. It considers all the days of the month and do not care about the day which is not passed yet.

The calendar.monthcalendar(year, month) method retrieves all the days of the month in a nested list format arranged based on the weeks. We will employ this according to the following approach:

  1. check if a Saturday exists in the last week of the month
  2. print it in case it exists
  3. else print out the Saturday from the second last week of the month

This approach is demonstrated in the following code:

Python3




from calendar import monthcalendar
  
# retrieving the required month 
# from the calendar
month = monthcalendar(2022, 12)
  
# checking if the last week of 
# the month has a saturday
if month[-1][5]:
    print(month[-1][-2])
  
# else print the saturday of the 
# second last week of the month  
else:
    print(month[-2][-2])


Output:

31

Find the last Saturday of the month Using the Datetime Module :

Date and time are not separate data types in Python, but they may be used together by importing the DateTime package. There is no requirement to install the Python Datetime Module outside because it is already included in Python. The DateTime module does not need to be installed as it already comes pre-installed with python.

Classes for working with date and time are provided by the Python Datetime module. Numerous capabilities to deal with dates, times, and time intervals are provided by these classes. Python treats date and DateTime as objects, so when you work with them, you’re really working with objects rather than strings or timestamps.

Six major classes make up the DateTime module:

  1. Date is an idealized naïve date that is based on the premise that the Gregorian calendar has always been and always will be used. The year, month, and day are its properties.
  2. Time is an idealistic period of time, independent of any specific day, where each day has exactly 24 hours and 60 minutes. Hour, minute, second, microsecond, and tzinfo are some of its properties.
  3. A combination of date and time, DateTime also includes the following properties: year, month, day, hour, minute, second, microsecond, and tzinfo.
  4. Timedelta: A duration that, down to the microsecond, expresses the difference between two dates, times, or DateTime occurrences.
  5. The time zone information object provider is tzinfo.
  6. Using a fixed offset from UTC, timezone is a class that implements the tzinfo abstract base class (New in version 3.2).

Constructor Syntax:  

class datetime.date(year, month, day)

The arguments must be in the following range –  

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year

Note: If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised. 

Now we follow the steps to solve this problem:

  • Import date and timedelta from datetime.
  • Find the last date of the month and store it in last_day.
  • Find offset by (today.weekday() – 5)%7 coz, 0 for Monday so, 5 for Saturday.
  • Find and print last Saturday from now by last_day – timedelta(days = offset).

Syntax: 

last_day - timedelta(days = offset)

where, 

  • last_day = last_day_of_month(year, month)
  • offset = (last_day.weekday() – 5)%7

Below is the implementation of the above approach:

Python3




from datetime import datetime
  
# Python program to find the last 
# day of the month in Python
  
def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None
      
# Python program to find the last 
# Saturday of the month in Python
      
from datetime import date
from datetime import timedelta
  
last_day = last_day_of_month(2022, 12)
  
offset = (last_day.weekday() - 5)%7
last_saturday = last_day - timedelta(days = offset)
  
print(last_saturday)


Output:
2022-12-31

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments