Python Code To Get Day Of Week
Chapter:
Python
Last Updated:
22-09-2023 04:49:45 UTC
Program:
/* ............... START ............... */
import datetime
# Create a datetime object for the desired date
date_string = "2023-09-22" # Replace with your date
date_obj = datetime.datetime.strptime(date_string, "%Y-%m-%d")
# Get the day of the week as an integer (0 = Monday, 6 = Sunday)
day_of_week = date_obj.weekday()
# You can also get the day of the week as a string
day_name = date_obj.strftime("%A")
print(f"The day of the week for {date_string} is {day_of_week} ({day_name}).")
/* ............... END ............... */
Output
The day of the week for 2023-09-22 is 4 (Friday).
In this example, September 22, 2023, is a Friday, so the program
correctly outputs "4 (Friday)" as the day of the week.
Notes:
-
In this program we use the datetime.datetime.strptime() method to parse the date_string into a datetime object. The %Y-%m-%d format string specifies the expected format of the date string, where %Y represents the year with century as a decimal number, %m represents the month as a zero-padded decimal number, and %d represents the day of the month as a zero-padded decimal number.
- date_obj.weekday() method to get the day of the week as an integer, where 0 represents Monday, 1 represents Tuesday, and so on, with 6 representing Sunday. The result is stored in the day_of_week variable.
- date_obj.strftime("%A") method to get the day of the week as a string, where "%A" is a format code that returns the full weekday name. The result is stored in the day_name variable.
- Finally, we print the result using an f-string, which allows us to insert the values of the variables into the string. The output includes the original date, the numeric day of the week, and the day name.
- Example output for the date "2023-09-22":
Tags
Python code to get day of week #How do you extract the day of the week in Python? #Python program to find day of the week for a given date