Open In App

Python program to find day of the week for a given date

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a Python program to extract weekdays from a given date for any particular date in the past or future. Let the input be in the format “dd mm yyyy”.

Example

Input : 03 02 1997 
Output : Monday
Input : 31 01 2019
Output : Thursday

The already discussed approach to extract weekdays from a given date for a given date is the Naive approach. Now, let’s discuss the Pythonic approaches. 

Extract Week Days From Given Date in Python

There are various ways to extract weekdays from a given date in Python, here we are discussing some generally used methods we used for extract weekdays from a given date in Python

Extract Week Days From Given Date in Python Using weekday() Method

In this method, weekday() function is provided by datetime module. The weekday() function of the date class in datetime module, returns an integer corresponding to the day of the week. 

Example: In this example, Python code defines a function `check_weekday_or_weekend` that takes a date string as input, converts it to a datetime object, determines the day of the week, and prints whether it’s a weekday or a weekend. The example usage checks the day type for the date ’03 02 2019′.

Python3




import datetime
import calendar
 
def check_weekday_or_weekend(date):
    try:
        # Convert the input date string to a datetime object
        given_date = datetime.datetime.strptime(date, '%d %m %Y')
         
        # Use isoweekday() to get the weekday (Monday is 1 and Sunday is 7)
        day_of_week = (given_date.weekday() + 1) % 7  # Convert Sunday from 6 to 0
         
        # Determine if it's a weekday or a weekend
        if day_of_week < 5:
            day_type = 'weekday'
        else:
            day_type = 'weekend'
         
        # Print the result
        print(f"The day of the week for {given_date.strftime('%Y-%m-%d')} is {day_of_week} ({day_type})")
         
    except ValueError as e:
        print(f"Error: {e}")
 
# Example usage
date = '03 02 2019'
check_weekday_or_weekend(date)


Output

The day of the week for 2019-02-03 is 0 (weekday)

Extract Week Days From Given Date in Python Using isoweekday() Method

The method uses the `isoweekday()` function in Python’s `datetime` module to extract the day of the week from a given date. The result is an integer where Monday is 1 and Sunday is 7. The code then categorizes the day as a weekday (1 to 5) or a weekend day (6 or 7).

Example : In this example code defines a function `check_weekday_or_weekend` that takes a date (specified by year, month, and day) as input, creates a datetime object, determines the day of the week (0 for Sunday to 6 for Saturday), and then prints whether it’s a weekday or a weekend. The example usage checks and prints the day type for the date December 20, 2023.

Python3




from datetime import datetime
 
def check_weekday_or_weekend(year, month, day):
    try:
        # Create a datetime object for the given date
        given_date = datetime(year, month, day)
         
        # Use isoweekday() to get the weekday (Monday is 1 and Sunday is 7)
        day_of_week = given_date.isoweekday() % 7  # Convert Sunday from 7 to 0
         
        # Determine if it's a weekday or a weekend
        if day_of_week < 5:
            day_type = 'weekday'
        else:
            day_type = 'weekend'
         
        # Print the result
        print(f"The day of the week for {given_date.strftime('%Y-%m-%d')} is {day_of_week} ({day_type})")
         
    except ValueError as e:
        print(f"Error: {e}")
 
# Example usage
year = 2023
month = 12
day = 20
 
check_weekday_or_weekend(year, month, day)


Output

The day of the week for 2023-12-20 is 3 (weekday)

Extract Week Days From Given Date in Python Using strftime() method

The strftime() method takes one or more format codes as an argument and returns a formatted string based on it. Here we will pass the directive “%A” in the method which provides Full weekday name for the given date. 

 Example : In this example code defines two functions using the `datetime` module. `check_weekday_or_weekend(date)` takes a date string as input, converts it to a `datetime.date` object, and returns “Weekday” if the day of the week is Monday to Friday, otherwise “Weekend.” `get_weekday_sunday_zero(date)` also converts the date string to a `datetime.date` object .

Python3




import datetime
 
def check_weekday_or_weekend(date):
    day, month, year = (int(i) for i in date.split(' '))   
    born = datetime.date(year, month, day)
    day_of_week = born.weekday()  # Monday is 0 and Sunday is 6
     
    if day_of_week < 5# Monday to Friday are weekdays
        return "Weekday"
    else:
        return "Weekend"
 
# Get weekday where Sunday is 0
def get_weekday_sunday_zero(date):
    day, month, year = (int(i) for i in date.split(' '))   
    born = datetime.date(year, month, day)
    day_of_week = born.weekday()  # Monday is 0 and Sunday is 6
    return day_of_week
 
# Driver program
date = '03 02 2019'
print("Is it a weekday or weekend?", check_weekday_or_weekend(date))
print("Weekday where Sunday is 0:", get_weekday_sunday_zero(date))


Output :

Is it a weekday or weekend? Weekend
Weekday where Sunday is 0: 6

Extract Week Days From Given Date in Python By Finding Day Number 

In this approach, we find the day number using calendar module and then find the corresponding week day. 
Example: In this example code defines a function `findDay` that takes a date string in the format ‘DD MM YYYY’, extracts day, month, and year, then uses the `calendar` module to determine the day of the week. It prints the day of the week for the provided date, in this case, ’03 02 2019′, which corresponds to Sunday.

Python3




import calendar
 
def findDay(date):
    day, month, year = (int(i) for i in date.split(' '))   
    dayNumber = calendar.weekday(year, month, day)
     
    # Modify days list to start with Sunday as 0
    days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
     
    return days[dayNumber]
 
# Driver program
date = '03 02 2019'
print(findDay(date))


Output

Saturday

Time Complexity: O(1) Auxiliary Space: O(1)

Extract Week Days From Given Date in Python Using Zeller’s Congruence

In this method the below code converts a date string into a datetime object using `strptime()`, extracts day, month, and year, and calculates the day of the week using Zeller’s congruence formula.

Example: In this example code defines two functions: `is_weekend` checks if a given date (in the format ‘day month year’) falls on a weekend (Saturday or Sunday), and `day_of_week` returns the day number (0 for Monday, 1 for Tuesday, …, 6 for Sunday) of a given date. The driver program uses these functions to determine and print whether a specific date (’03 02 2019′) is a weekend or weekday .

Python3




from datetime import datetime
 
def is_weekend(date_str):
    date_obj = datetime.strptime(date_str, '%d %m %Y')
    day_num = date_obj.weekday()  # 0 for Monday, 1 for Tuesday, ..., 6 for Sunday
    return day_num >= 5  # Returns True if it's Saturday or Sunday, indicating a weekend
 
def day_of_week(date_str):
    date_obj = datetime.strptime(date_str, '%d %m %Y')
    day_num = date_obj.weekday()  # 0 for Monday, 1 for Tuesday, ..., 6 for Sunday
    return day_num
 
# Driver program
date_str = '03 02 2019'
weekday_num = day_of_week(date_str)
 
if is_weekend(date_str):
    print(f"{weekday_num} (Sunday is 0) - It's a weekend.")
else:
    print(f"{weekday_num} (Sunday is 0) - It's a weekday.")


Output

6 (Sunday is 0) - It's a weekend.

Time Complexity: O(1)
Space Complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads