Python calendar weekday() Method with Example

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

Python calendar.weekday() Method

The calendar.weekday() method is an inbuilt method of the calendar module, it returns the day of the week for the given year, month, and day mentioned in the function argument. Here Monday denotes 0 and increments the following days by one for the year (1970 - …), month (1 - 12), and day (1 - 31).

Module

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

import calendar

Syntax

The following is the syntax of weekday() method:

weekday(year, month, day)

Parameter(s)

The following are the parameter(s):

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

Return Value

The return type of this method is <class 'int'>, it returns a number which is the day on this given year, month and day. Monday is 0 and Sunday is 6.

Example of calendar.weekday() Method in Python

# Python program to illustrate the 
# use of weekday() method
  
# importing calendar module 
import calendar 

year = 2020
month = 2
day = 20
x = calendar.weekday(year, month, day)
print("Weekday number for the given date:", x)
print()

# We can also make a list of days and 
# print the day name accordingly
wday = ['Monday', "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
year = 1996
month = 10
day = 27
x = calendar.weekday(year, month, day)
print("Weekday number:", x)
print("Weekday name:", wday[x])

Output

Weekday number for the given date: 3

Weekday number: 6
Weekday name: Sunday

Note: The date in the function argument should be valid, otherwise it will raise a ValueError.

For example, if you print 31 September 2019, this will be wrong as September has only 30 days.

Example 2

# Python program to illustrate the 
# use of weekday() method
  
# importing calendar module 
import calendar 

year = 2019
month = 2
day = 29

x = calendar.weekday(year, month, day)

print("Weekday number for the given date:", x)

print()

Output

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    x = calendar.weekday(year, month, day)
  File "/usr/lib/python3.8/calendar.py", line 117, in w
eekday
    return datetime.date(year, month, day).weekday()
ValueError: day is out of range for month

Comments and Discussions!

Load comments ↻





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