ADVERTISEMENT
ADVERTISEMENT

Python calendar Module | monthrange() Method with Example

Python calendar.monthrange() Method: Here, we are going to learn about the monthrange() method of calendar module in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 08, 2020

Python calendar.monthrange() Method

monthrange() method is an inbuilt method of the calendar module in Python. It works on the simple text calendars and returns a tuple where the first value is the weekday of first day of the month and the second value is the number of days in month, for the specified year and month.

Module:

    import calendar

Syntax:

    monthrange(year, month)

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:

# 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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.