Skip to main content

How to get the day of the week from a given date in Python

How to get the day of the week from a given date in Python.

Here is a step-by-step tutorial on how to get the day of the week from a given date in Python:

Step 1: Import the necessary modules To begin, you need to import the datetime module in Python. This module provides classes for working with dates and times.

import datetime

Step 2: Get the input from the user Next, you need to ask the user to input a specific date. You can use the input() function to get the date as a string from the user.

date_string = input("Enter a date (YYYY-MM-DD): ")

Step 3: Convert the input to a date object Now, you need to convert the user's input into a datetime object. You can use the strptime() function from the datetime module to parse the date string according to the specified format.

date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")

Step 4: Extract the day of the week To get the day of the week from the given date, you can use the strftime() function with the format code %A. This code will return the full name of the day of the week.

day_of_week = date_object.strftime("%A")

Step 5: Print the result Finally, you can print the day of the week to the console.

print("The day of the week is", day_of_week)

Complete code example:

import datetime

date_string = input("Enter a date (YYYY-MM-DD): ")

date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
day_of_week = date_object.strftime("%A")

print("The day of the week is", day_of_week)

This code will prompt the user to enter a date in the format YYYY-MM-DD. It will then convert the input into a datetime object and extract the day of the week using the %A format code. Finally, it will print the result to the console.