How to Validate Weekend Dates in Python
Validating whether a specific date falls on a weekend is a common requirement in business logic, scheduling applications, and data analysis. Python provides robust tools within the datetime and calendar modules to handle this efficiently.
This guide explains how to identify weekends (typically Saturday and Sunday) using Python's weekday indexing, along with practical examples for date ranges and error handling.
Understanding Weekday Indexing
In Python's standard library, days of the week are represented as integers. It is crucial to know the mapping to correctly identify weekends.
- Monday:
0 - Tuesday:
1 - Wednesday:
2 - Thursday:
3 - Friday:
4 - Saturday:
5(Weekend) - Sunday:
6(Weekend)
Therefore, any date with a weekday index greater than or equal to 5 is a weekend.
Method 1: Using the datetime Module (Recommended)
The datetime module is the most direct way to check a date. The .weekday() method returns the integer corresponding to the day of the week.
Example of Basic Check:
from datetime import date, datetime
def is_weekend(d):
# Check if the date object is valid
if not isinstance(d, (date, datetime)):
raise TypeError("Input must be a date or datetime object")
# 5 = Saturday, 6 = Sunday
return d.weekday() >= 5
# ✅ Correct: Checking specific dates
friday = date(2025, 12, 26)
saturday = date(2025, 12, 27)
print(f"{friday}: Is weekend? {is_weekend(friday)}")
print(f"{saturday}: Is weekend? {is_weekend(saturday)}")
Output:
2025-12-26: Is weekend? False
2025-12-27: Is weekend? True
There is also a .isoweekday() method where Monday is 1 and Sunday is 7. If you use that, the check would be d.isoweekday() >= 6. Sticking to .weekday() (0-6) is generally preferred for consistency.
Method 2: Using the calendar Module
If you are working with raw integers (year, month, day) rather than date objects, the calendar module provides a helper function weekday(year, month, day) that returns the specific code without creating a full date object first.
import calendar
def check_weekend_raw(year, month, day):
try:
# Returns 0-6 (Monday-Sunday)
day_code = calendar.weekday(year, month, day)
if day_code >= 5:
return "Weekend"
return "Weekday"
except ValueError as e:
return f"Invalid Date: {e}"
# ✅ Correct: Checking raw values
print(f"2025-12-21: {check_weekend_raw(2025, 12, 21)}") # Sunday
print(f"2025-12-22: {check_weekend_raw(2025, 12, 22)}") # Monday
# ⛔️ Error Case: Invalid day
print(f"2025-02-30: {check_weekend_raw(2025, 2, 30)}")
Output:
2025-12-21: Weekend
2025-12-22: Weekday
2025-02-30: Invalid Date: day is out of range for month
Practical Example: Generating Weekend Lists
A common real-world task is finding all weekend dates within a specific timeframe (e.g., for scheduling purposes).
from datetime import date, timedelta
def get_weekends_in_range(start_date, days_count):
weekends = []
for i in range(days_count):
current_date = start_date + timedelta(days=i)
# Check if Saturday (5) or Sunday (6)
if current_date.weekday() >= 5:
weekends.append(current_date)
return weekends
# Generate weekends for the next 10 days starting from today
today = date.today()
weekend_list = get_weekends_in_range(today, 10)
print(f"Start Date: {today}")
print("Upcoming Weekend Dates:")
for day in weekend_list:
print(f"- {day} ({day.strftime('%A')})")
Output (Example):
Start Date: 2025-12-28
Upcoming Weekend Dates:
- 2025-12-28 (Sunday)
- 2026-01-03 (Saturday)
- 2026-01-04 (Sunday)
Conclusion
Validating weekends in Python relies on understanding the weekday integer mapping:
- Use
date.weekday() >= 5when working withdatetimeobjects. - Use
calendar.weekday(y, m, d) >= 5when working with raw integers to avoid object overhead. - Always Validate Inputs to ensure the date actually exists (e.g., February 30th) before checking the day of the week.