Get Month from year and weekday using Python


Dealing with time is one of the most important aspects of any day−to−day activity. In this article, we will discuss how to get month from year and weekday using Python. We will utilize Python's two most popular libraries, namely calendar, and datetime, to deal with the months, year,s, etc. Both libraries provide several in−built methods to deal with time. We do not need to exclusively care for challenging tasks like leap year if we deal with such libraries.

Using The Calendar Library

The calendar library in Python provides useful functions and classes working with the calendar and the dates. It offers a range of functionalities to generate calendars, manipulate dates, and perform calendar−related calculations. It simplifies tasks related to generating calendars, calculating weekdays, and manipulating dates, making it a valuable tool for handling calendar−related operations in various applications.

Example

In the following example, we have first imported the calendar module in our code. Next, we have defined a function that takes the year and the weekday as an Integer and String, respectively. We iterated 12 times, and under each iteration, we accessed the first day of the weekday using the weekday method. Next, we checked the first day of the month, equal to the given weekday. We returned the corresponding month.

import calendar
def get_month(year, weekday):
    for month in range(1, 13):
        _, days = calendar.monthrange(year, month)
        first_day_weekday = calendar.weekday(year, month, 1)
        if calendar.day_name[first_day_weekday] == weekday:
            return calendar.month_name[month]
    return None
year = 2023
weekday = 'Monday'
month = get_month(year, weekday)
if month:
    print(f"The month with {weekday}s as the first weekday in {year} is {month}.")
else:
    print(f"There is no {weekday} as the first weekday in any month of {year}.")

Output

The month with Mondays as the first weekday in 2023 is May.

Using The Datetime and Timedelta Modules

The timedelta module in Python provides functionality for working with time differences or durations. It allows you to perform arithmetic operations on dates and times, such as adding or subtracting time intervals. Since the time is a different type compared to the integers, normal operations do not apply to them.

Example

In the following code, we first imported the datetime and timedelta modules. Next, we created a user−defined function named get_month. The function takes the year and weekday as the parameter. We iterated from 1 to 13 (13 excluded). Under each iteration, the code compares the weekday of first_day with the weekday parameter passed to the function. It does this by calling the strftime('%A') method on first_day to format the date as the full weekday name (e.g., Monday, Tuesday, etc.).

from datetime import datetime, timedelta

def get_month(year, weekday):
    for month in range(1, 13):
        first_day = datetime(year, month, 1)
        if first_day.strftime('%A') == weekday:
            return first_day.strftime('%B')
year = 2023
weekday = 'Saturday'
month = get_month(year, weekday)
if month:
    print(f"The month with {weekday}s as the first weekday in {year} is {month}.")
else:
    print(f"There is no {weekday} as the first weekday in any month of {year}.")

Output

The month with Saturdays as the first weekday in 2023 is April.

Using The weekday Method

The weekday() method is a function available in the datetime module in Python. We use this to determine the weekday. The method returns an integer representing the weekday, where Monday is 0, and Sunday is 6. By calling the weekday() method on a datetime.date object, you can easily retrieve the weekday information and use it for various date−related calculations and manipulations in your Python programs.

Example

In the given an example, the function find_month_with_weekday method takes two parameters: year (the year) and weekday. It iterates over each month in the given year using a for loop that ranges from 1 to 13. It checks if the weekday of first_day matches the specified weekday using the .weekday() method, which returns an integer representing the weekday. Here Monday is represented by 0, Tuesday by one, and so on. If a match is found, it returns the month name of first_day using .strftime("%B"), which formats the date as the full month name.

import datetime

def find_month_with_weekday(year, weekday):
    for month in range(1, 13):
        first_day = datetime.date(year, month, 1)
        if first_day.weekday() == weekday:
            return first_day.strftime("%B")
    return None
test_year = 2023
test_weekday = 3 
result = find_month_with_weekday(test_year, test_weekday)
if result:
    print(f"The month with {datetime.date(test_year, 1, 1 + test_weekday).strftime('%A')} as the first weekday in {test_year} is {result}.")
else:
    print(f"No month with {datetime.date(test_year, 1, 1 + test_weekday).strftime('%A')} as the first weekday found in {test_year}.")

Output

The month with Wednesday as the first weekday in 2023 is June.

Conclusion

In this article, we learned how to get the month from year to weekday using Python. Python offers us several libraries for time, like datetime, calendar, etc. It also allows us to deal easily with the weeks, months, etc. Hence we can use the combination of these libraries and other Python logic to access the month from year to weekday.

Updated on: 18-Jul-2023

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements