Open In App

Python – Last business day of every month in year

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a year and weekday number, the task is to write a Python program to extract each date of the month corresponding to the weekday.

Input : year = 1997, weekdy = 5

Output : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]

Explanation : 5 is friday. Last weekday of january 1997 which is friday is 25.

Input : year = 1996, weekdy = 4

Output : [’26/1/1996′, ’23/2/1996′, ’29/3/1996′, ’26/4/1996′, ’31/5/1996′, ’28/6/1996′, ’26/7/1996′, ’30/8/1996′, ’27/9/1996′, ’25/10/1996′, ’29/11/1996′, ’27/12/1996′]

Explanation : 4 is thursday. Last weekday of january 1997 which is thursday is 26.

Method #1 : Using loop + max() + calendar.monthcalendar

In this, we perform the task of getting each month calendar using monthcalendar() from the calendar library. Each weekday date is extracted and the maximum of it, being the maximum of the whole month is the last weekday, hence extracted.

Python3




# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using loop + max() + calendar.monthcalendar
import calendar
 
# initializing year
year = 1997
 
# printing Year
print("The original year : " + str(year))
 
# initializing weekday
weekdy = 5
 
# iterating for all months
res = []
for month in range(1, 13):
     
    # max gets last friday of each month of 1997
    res.append(str(max(week[weekdy]
                       for week in calendar.monthcalendar(year, month))) +
               "/" + str(month)+ "/" + str(year))
 
# printing
print("Last weekdays of year : " + str(res))


Output:

The original year : 1997

Last weekdays of year : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]

Method #2: Using list comprehension

Similar to the above method, the only difference being the usage of list comprehension for a compact solution.

Python3




# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using list comprehension
import calendar
 
# initializing year
year = 1997
 
# printing Year
print("The original year : " + str(year))
 
# initializing weekday
weekdy = 5
 
# list comprehension for shorthand
res = [str(max(week[weekdy]
               for week in calendar.monthcalendar(year, month))) +
       "/" + str(month)+ "/" + str(year) for month in range(1, 13)]
 
# printing
print("Last weekdays of year : " + str(res))


Output:

The original year : 1997

Last weekdays of year : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]

The time complexity of this program is O(12*w*m) where w is the number of weekdays and m is the number of months.

The auxiliary space complexity of the program is O(m) where m is the number of months.

Method #3: Using pandas library

Use the pandas library to create a date range for the entire year, and then filter out the last weekday of each month using the weekday and is_month_end methods. Here’s how you can modify the code using pandas.

Python3




import pandas as pd
 
# initializing year
year = 1997
 
# printing Year
print("The original year : " + str(year))
 
# initializing weekday
weekdy = 4  # 4 represents Friday in pandas
 
# creating a date range for the entire year
dates = pd.date_range(start=f'{year}-01-01', end=f'{year}-12-31', freq='D')
 
# filtering out the last weekday of each month
res = [str(date.date()) for date in dates[(dates.weekday == weekdy) & (dates.is_month_end)]]
 
# printing
print("Last weekdays of year : " + str(res))


The original year : 1997
Last weekdays of year : ['1997-01-31', '1997-02-28', '1997-10-31']

Time complexity: O(n), where n is the number of days in the given year.
Auxiliary space: O(n), as we create a pandas date range object for the entire year and store it in memory.

Method #4: Using datetime and timedelta from datetime module

 step-by-step approach :

  1. First, we initialize the year and weekday variables. In this example, year is set to 1997 and weekday is set to 4, which represents Friday.
  2. We create an empty list called last_weekdays to store the last weekdays of each month.
  3. We iterate over the months of the year using a for loop. The loop runs 12 times, once for each month.
  4. For each month, we get the last day of the month using the datetime and timedelta classes. We start by creating a datetime object for the first day of the month using the datetime class.
  5. We then add 32 days to this datetime object using the timedelta class. This brings us to a date beyond the end of the month, which ensures that we get the last day of the month even if it’s a leap year (since February can have 29 days).
  6. We replace the day component of the resulting datetime object with 1 and then subtract 1 day using timedelta to get the last day of the month.
  7. We check if the last day of the month is the same weekday as the desired weekday. If it is, we append the date to the last_weekdays list.
  8. Finally, we print the results.

Python3




from datetime import datetime, timedelta
 
# initializing year and weekday
year = 1997
weekday = 4 # 4 represents Friday
 
# creating a list to store the last weekdays of each month
last_weekdays = []
 
# iterating over the months of the year
for month in range(1, 13):
    # getting the last day of the month
    last_day = datetime(year, month, 1) + timedelta(days=32)
    last_day = last_day.replace(day=1) - timedelta(days=1)
     
    # checking if the last day is the same weekday as the desired weekday
    if last_day.weekday() == weekday:
        # adding the date to the list
        last_weekdays.append(last_day.date())
 
# printing the results
print(f"Last weekdays of year: {last_weekdays}")


Output

Last weekdays of year: [datetime.date(1997, 1, 31), datetime.date(1997, 2, 28), datetime.date(1997, 10, 31)]

The time complexity of this method is O(1) since it only needs to iterate over the months once.

The auxiliary space is O(1) since only a few variables are stored in memory.

Method #5: Using dateutil library

Step-by-step approach:

  1. Import the necessary module from dateutil library
  2. Initialize year and weekday (same as in the original code)
  3. Create a list of datetime objects for every month in the year
  4. Filter the list to include only the datetime objects for the last weekday of the month
  5. Format the datetime objects as strings in the required format
  6. Return the list of formatted strings

Python3




# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using dateutil library
 
from dateutil import rrule, relativedelta
from datetime import datetime
 
# initializing year
year = 1997
 
# printing Year
print("The original year : " + str(year))
 
# initializing weekday
weekdy = 5
 
# create a list of datetime objects for every month in the year
months = [datetime(year, month, 1) for month in range(1, 13)]
 
# filter the list to include only the datetime objects for the last weekday of the month
last_weekdays = [dt.strftime('%d/%m/%Y') for dt in months if dt.weekday() == weekdy
                                                       and dt + relativedelta.relativedelta(months=1, days=-1)]
 
# printing
print("Last weekdays of year : " + str(last_weekdays))


OUTPUT ;
The original year : 1997
Last weekdays of year : ['01/02/1997', '01/03/1997', '01/11/1997']

Time complexity: O(1) as the list of datetime objects has a fixed length of 12 (number of months)
Auxiliary space: O(1) as the memory usage is constant and does not depend on the size of input.



Previous Article
Next Article

Similar Reads

Python program to print current year, month and day
In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date classCall the today( ) function of date class to fetch
1 min read
Pandas Series dt.is_month_end | Check if Date is Last Day of Month
Pandas dt.is_month_end attribute returns a boolean value indicating whether the date is the last day of the month. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-1-31', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-1-1 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr)
2 min read
Find number of times every day occurs in a Year
Given a year .Your task is to find the number of every day in a year ie.number of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday in that given year.Examples: Input: 2019 Output: Monday-52 Tuesday-53 Wednesday-52 Thursday-52 Friday-52 Saturday-52 Sunday-52 Input: 2024 Output: Monday-53 Tuesday-53 Wednesday-52 Thursday-52 Friday-52 Sa
6 min read
Python program to Get Month Name from Month Number
Given a datetime object or month number, the task is to write a Python program to get the corresponding month name from it. Examples: Input : test_date = datetime(2020, 4, 8)Output : AprilExplanation : 4th Month is April. Input : test_date = datetime(2020, 1, 8)Output : JanuaryExplanation : 1st Month is January. Method #1 : Using strftime() + %B In
4 min read
Pandas Series dt.month | Extract Month Part From DateTime Series
The dt.month attribute returns a NumPy array containing the month of the DateTime in the underlying data of the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = id
2 min read
Get month and Year from Date in Pandas - Python
Pandas is one of the most powerful library in Python which is used for high performance and speed of calculation. It is basically an open-source BSD-licensed Python library. Commonly it is used for exploratory data analysis, machine learning, data visualization in data science, and many more. It has very dynamic and easy to understand syntax which
4 min read
Python program to calculate Date, Month and Year from Seconds
Given the number of seconds, the task is to write a Python program to calculate the date, month, and year in the format MM-DD-YYYY that have been passed from 1 January 1947. Examples Input: 0 Output: 01-01-1947 Input: 123456789 Output: 11-29-1950 Input: 9876543210 Output: 12-22-2259Approach to Calculate Date, Month, and Year from SecondsHere is the
4 min read
Python - Get Month from year and weekday
Given a year and weekday, the task is to write a Python program to get a month and the week. Example: Input : test_year = 1997, test_week = 27 Output : 1997-07-07 00:00:00 Explanation : 27th Week starts from 7 july in 1997. Input : test_year = 2021, test_week = 27 Output : 2021-07-05 00:00:00 Explanation : 27th Week starts from 5 july in 2021. Meth
5 min read
Pandas Series dt.is_month_start | Check if Date is First Day of Month
The dt.is_month_start attribute returns a boolean value indicating whether the date is the first day of the month.ExamplePython3 import pandas as pd sr = pd.Series(['2012-1-1', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-1-1 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result
2 min read
Python program to find the first day of given year
Given a year as input, write a Python to find the starting day of the given year. We will use the Python datetime library in order to solve this problem. Example: Input : 2010 Output :FridayInput :2019 Output :Tuesday Below is the implementation: C/C++ Code # Python program to find the first day of given year # import datetime library import dateti
2 min read
Practice Tags :