check if given date is saturday or sunday in python

You can use the weekday() method from the datetime module in Python to check if a given date is a Saturday or Sunday. The weekday() method returns an integer where Monday is 0 and Sunday is 6.

Here is an example of how to check if a given date is a Saturday or Sunday:

main.py
from datetime import datetime

def is_weekend(date_string):
    # Convert the date string to a datetime object
    date_object = datetime.strptime(date_string, "%Y-%m-%d")
  
    # Get the weekday as an integer where Monday is 0 and Sunday is 6
    weekday = date_object.weekday()
  
    # Check if the date is a Saturday or Sunday
    if weekday == 5 or weekday == 6:
        return True
    else:
        return False

# Example usage
date = "2021-11-21"  # Sunday
if is_weekend(date):
    print(f"{date} is a weekend.")
else:
    print(f"{date} is not a weekend.")
568 chars
22 lines

This will output:

main.py
2021-11-21 is a weekend.
25 chars
2 lines

Alternatively, you can also use the strftime method to directly format the date object and check if it matches "Saturday" or "Sunday" strings:

main.py
from datetime import datetime

def is_weekend(date_string):
    # Convert the date string to a datetime object
    date_object = datetime.strptime(date_string, "%Y-%m-%d")
  
    # Format the date object as a string
    formatted_date = date_object.strftime("%A")
  
    # Check if the date is a Saturday or Sunday
    if formatted_date == "Saturday" or formatted_date == "Sunday":
        return True
    else:
        return False

# Example usage
date = "2021-11-21"  # Sunday
if is_weekend(date):
    print(f"{date} is a weekend.")
else:
    print(f"{date} is not a weekend.")
581 chars
22 lines

This will output the same result as before:

main.py
2021-11-21 is a weekend.
25 chars
2 lines

Remember to replace the date_string variable with the date you want to check in the format "YYYY-MM-DD".

gistlibby LogSnag