Home > Backend Development > Python Tutorial > How Can I Find the Last Day of a Month in Python?

How Can I Find the Last Day of a Month in Python?

DDD
Release: 2024-12-02 06:47:10
Original
510 people have browsed it

How Can I Find the Last Day of a Month in Python?

Determining the Last Day of a Month in Python

Python's standard library provides several utilities for working with calendar functions. One such function, calendar.monthrange, can be used to easily determine the last day of a specified month.

The calendar.monthrange function takes two arguments: the year and the month, and returns a tuple containing the weekday of the first day of the month and the number of days in the month. The last day of the month can be obtained by accessing the second item in the tuple.

import calendar

year = 2023
month = 2

weekday, days_in_month = calendar.monthrange(year, month)
last_day = days_in_month
Copy after login

The dateutil package also provides functionality for working with calendar dates. However, Python's standard library functions are sufficient for this particular task.

To summarize, the following snippet can be used to get the last day of a month using Python's standard library:

import calendar

def get_last_day_of_month(year, month):
    weekday, days_in_month = calendar.monthrange(year, month)
    return days_in_month
Copy after login

The above is the detailed content of How Can I Find the Last Day of a Month in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template