weekday() Function Of Datetime.date Class In Python
The weekday() function is a built-in method of the datetime.date class in Python. It returns the day of the week as an integer, where Monday is 0 and Sunday is 6. This method is useful when you want to determine the day of the week for a given date. Example:
from datetime import date
d = date(2025, 5, 8)
print(d.weekday())
Output
3
Explanation: date(2025, 5, 8) represents May 8, 2025. Since Thursday is the 4th day of the week (starting from Monday as 0), it returns 3.
Syntax of weekday()
date_object.weekday()
Parameter: No parameters are required. This method is called on a date object.
Return values: This function returns the integer mapping corresponding to the specified day of the week. Below table shows the integer values corresponding to the day of the week.
Integer returned by weekday() function | Day of the week |
---|---|
0 | Monday |
1 | Tuesday |
2 | Wednesday |
3 | Thursday |
4 | Friday |
5 | Saturday |
6 | Sunday |
Example of weekday()
Example 1: In this example, we use the weekday() method to find out what day of the week January 1, 2025 falls on, then match that number to a weekday name using a list.
from datetime import date
a = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
d = date(2025, 1, 1)
print(a[d.weekday()])
Output
Wednesday
Explanation: d.weekday() returns 2 because January 1, 2025 is a Wednesday, and in the list a, index 2 corresponds to "Wednesday".
Example 2: In this example, we use the weekday() method on two dates to find which one falls earlier in the week, where Monday is 0 and Sunday is 6.
from datetime import date
a = date(2025, 1, 1) # Wednesday
b = date(2025, 1, 4) # Saturday
print(a.weekday())
print(b.weekday())
print(a.weekday() < b.weekday())
Output
2 5 True
Explanation:
- a.weekday() returns 2, which means January 1, 2025 is a Wednesday.
- b.weekday() returns 5, meaning January 4, 2025 is a Saturday.
- a.weekday() < b.weekday() checks if Wednesday comes before Saturday in the week, which is True.
Example 3: We use the weekday() method here to check if a date falls on a weekend by comparing its result (0 for Monday to 6 for Sunday) with >= 5, which indicates Saturday or Sunday.
from datetime import date
d1 = date(2025, 5, 10) # Saturday
d2 = date(2025, 5, 12) # Monday
print(d1.weekday() >= 5)
print(d2.weekday() >= 5)
Output
True False
Explanation:
- d1.weekday() is 5 (Saturday), so d1.weekday() >= 5 returns True.
- d2.weekday() is 0 (Monday), so d2.weekday() >= 5 returns False.