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).
Hi!
First of all thank you for sharing your code!
I used it to automate a spreadsheet and found out that if you run the algorithm on a Saturday trying to find last Saturday it returns the current day. So the way I solved it was running it like this:
today = date.today()
for i in range(0, 7):
if today.weekday() == i:
offset = i + 2
last_saturday = today – timedelta(days = offset)
This is for finding Saturday, but you can change the ‘offset’ according to the day you would like to find. For last Friday, for example, offset should be i + 3.
I wanted to share this because it took me a minute figuring it out and this might save other people some time. I also never really understood the whole ‘%7’ command. At first I thought if the offset for finding last saturday was offset = (today.weekday() – 5)%7 then for finding last friday it would be something like offset = (today.weekday() – 6)%7. Anyway… I hope this helps.
Lucas
Thanks for the time to share your thoughts.