How to find the last Saturday of the month in Pyhton

In this tutorial, we will talk about How to find the last Saturday or any other day of the month in Python. So in order to understand this tutorial first, we need to understand about Calendar. As already told on my previous blog you can visit in order to understand basic calendar functions. Here’s the link https://www.codespeedy.com/find-first-sunday-of-the-month-in-python

Datetime class

Datetime is an object so when you try to change them it doesn’t change  string. Whenever you need to change date and time you are suppose to import datetime fucntion .

Types of date time

  • date – Use to find dates (Month,day,year)
  • time – Use to find time (Hour,Minute,second)
  • datetime –  Combination of both date and time
  • tzinfo – An abstract class which deals with time zone
  • timedelta – It is use to  manipulate date and time

Basic calendar code

How to find current date and time 

import time 
import datetime
print("Current date and time is: " ,datetime.datetime.now())
Output:
Current date and time is: 2019-07-07 18:10:54 

To find Current year

import time 
import datetime
print("Current year is:" datetime.date.today().strftime("%Y"))
Output:
Current year is : 2019

How to find Last Saturday of the month in Python

 

from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 5)%7
last_saturday = today - timedelta(days=offset)
print(last_saturday)
Output:
2019-07-06

As written in the above code in order to manipulate date and time we need to import datetime function. Timedelta function being import from datetime fucntion so that it can also be used to show future or previous dates in the calendar. This code is easily changeable and can be used to find out any day by changing number of days in line number 4. for example if you want to find last Wednesday just change 5 to 2 (Monday – 0, Sunday – 6).

 

Leave a Reply

Your email address will not be published. Required fields are marked *