Python calendar monthrange() Method with Example

Python calendar.monthrange() Method: In this tutorial, we will learn about the monthrange() method of calendar module in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 24, 2023

Python calendar.monthrange() Method

The calendar.monthrange() method is an inbuilt method of the calendar module, it returns a tuple where the first value is the weekday of the first day of the month and the second value is the number of days in the month, for the specified year and month.

Module

The following module is required to use monthrange() method:

import calendar

Syntax

The following is the syntax of monthrange() method:

monthrange(year, month)

Parameter(s)

The following are the parameter(s):

  • year: It is a required parameter, which represents the year of the calendar.
  • month: It is a required parameter, which represents the month of the calendar.

Return Value

The return type of this method is <class 'tuple'>, where first value is the weekday number of the first day of the month and the second value is the number of days in that month.

Example of calendar.monthrange() Method in Python

# Python program to illustrate the 
# use of monthrange() method

# importing calendar module
import calendar

year = 2020
month = 4

print("The first weekday number of the April 2020 and number of days in April:", calendar.monthrange(year, month))
print()
# Prints (2, 30) where 2 is the first 
# weekday number and 30 is the number of days in April

# We can store the values separately
year = 2010
month = 10
x, y = calendar.monthrange(year, month)
print("First weekday number:", x)
print("Number of days in this month:", y)
print()

# We can also print the WEEKDAY name
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
year = 2019
month = 12
x, y = calendar.monthrange(year, month)
print("First weekday number", x)
print("Number of days in this month:", y)
print("Weekday was:", days[x])
print()

Output

The first weekday number of the April 2020 and number of days in April: (2, 30)

First weekday number: 4
Number of days in this month: 31

First weekday number 6
Number of days in this month: 31
Weekday was: Sunday

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.