In this article, we will see how to find the day of the week from a date provided by the user.

Using Python’s built-in datetime module, we can determine the day of the week from a given date.

Let’s first import the datetime module and create datetime object with the desired date.

import datetime
date = datetime.datetime(2023, 5, 14)

By using the strftime() function we can format the given date and retrieve the day of the week.

day_of_week = date.strftime('%A')
print("The day of the week is:", day_of_week)

As an alternative way, we can also get the day of the week from the given date using the calender module.

Import that calendar module & use the weekday() function to find the day of the week. This function takes the year, month, and day as parameters and returns an integer representing the day of the week (0 for Monday, 1 for Tuesday, and so on).

Using the calender module’s list of weekday names, retrieve the actual day of the week.

Following is the example:

import calendar
day_of_week_index = calendar.weekday(2023, 5, 14)
day_of_week = calendar.day_name[day_of_week_index]
print("The day of the week is:", day_of_week)

Categorized in:

Tagged in: