Home  >  Article  >  Backend Development  >  Get month of year and day of week using Python

Get month of year and day of week using Python

WBOY
WBOYforward
2023-09-15 17:41:02844browse

Get month of year and day of week using Python

Processing time is one of the most important aspects of any daily activity. In this article, we will discuss how to get month from year and weekday using Python. We will make use of two of Python's most popular libraries, calendar and datetime, to handle months, years, etc. Both libraries provide several built-in methods for handling time. If we deal with such a library, we don't need to care specifically about challenging tasks like leap years.

Using Calendar Library

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

Example

In the example below, we first import the calendar module in the code. Next, we define a function that takes the year and weekday as an integer and a string respectively. We iterate 12 times, and on each iteration we access the first day of the weekday using the weekday method. Next, we check for the first day of the month, which equals the given working day. 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 Datetime and Timedelta modules

The timedelta module in Python provides functions for handling time differences or durations. It allows you to perform arithmetic operations on dates and times, such as adding or subtracting time intervals. Since times are a different type compared to integers, normal operations don't work on them.

Example

In the code below, we first import the datetime and timedelta modules. Next, we created a user-defined function called get_month. This function takes the year and the weekday as parameters. We iterate from 1 to 13 (excluding 13). On each iteration, the code compares the weekday of first_day to the weekday parameter passed to the function. It does this by calling the strftime('%A') method on first_day to format the date to 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.

Use workday method

The weekday() method is a function in the datetime module in Python. We use this to determine working days. This method returns an integer representing the working day, where Monday is 0 and Sunday is 6. By calling the weekday() method on a datetime.date object, you can easily retrieve weekday information and use it in a variety of date-related calculations and operations in Python programs.

Example

In the given example, the function find_month_with_weekday method takes two parameters: year and weekday. It iterates over each month of the given year using a for loop ranging from 1 to 13. It checks whether 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 is represented by 1, and so on. If a match is found, it returns the month name for first_day using .strftime("%B") , which formats the date to 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.

in conclusion

In this article, we learned how to get the month and weekday of the year using Python. Python provides us with several libraries for time, such as datetime, calendar, etc. It also allows us to easily handle weeks, months, etc. So we can use a combination of these libraries and other Python logic to access the months from year to year. working days.

The above is the detailed content of Get month of year and day of week using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete