Check If Date Is Weekend In Python

This tutorial will discuss about a unique way to check if date is weekend in Python.

Suppose you are working on a Python application and you need to make decisions based on the fact that today is a Weekend or not. basically you need to check if today is either Saturday or Sunday.

Suppose you have a date in string format like this,

dateStr = '2023-04-23'

To check if this date falls on a weekend or not, We have created a method,

from datetime import datetime

def is_weekend(dateStr):
    # Checks if a given date string is a weekend.
    # Returns True, if given date string is a weekend, False otherwise.
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()
    return dateObj.weekday() >= 5

It accepts a date in the string format, and checks if the given date is a weekend or not. It returns True if they given date string is a weekend, otherwise returns False.

Basically, first it converts the date in string format into a date type (from the datetime module). Then it uses the weekday() method of the date class to check if the given date is either Saturday or Sunday. Basically if the weekday is either 5 or 6, then it means that it Saturday or Sunday.

We can use this method to check if this given date string is weekend or not.

Let’s see the complete example,

from datetime import datetime

def is_weekend(dateStr):
    # Checks if a given date string is a weekend.
    # Returns True, if given date string is a weekend, False otherwise.
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()
    return dateObj.weekday() >= 5

# Example 1
dateStr = '2023-04-23'

# Output: True (because it is Sunday)
print(is_weekend(dateStr))

# Example 2
dateStr = '2023-04-26'

# Output: False (because it is Monday)
print(is_weekend(dateStr))

Output

True
False

Summary

We learned about a way to check if the Date is Weekend In Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top