Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month, and year respectively. The output should be the name of the day of the week in English (e.g., “Sunday”, “Monday”).
To determine the day of the week for a given date, we can make use of Python’s datetime
module. This module provides convenient methods to handle dates and can directly give us the day of the week.
Steps:
datetime
module.datetime.date(year, month, day)
.weekday()
method of the date object to get the day of the week as an integer (0 = Monday, …, 6 = Sunday).import datetime
def dayOfTheWeek(day: int, month: int, year: int) -> str:
# Create date object
date = datetime.date(year, month, day)
# Map of week day index to the day name
day_map = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# Get the day of the week as an integer (0-6, Monday-Sunday)
day_index = date.weekday()
# Return the corresponding day name
return day_map[day_index]
# Example Usage
print(dayOfTheWeek(31, 8, 2019)) # Output: "Saturday"
This approach takes advantage of Python’s built-in datetime
module, which is optimized and reliable for handling dates and calculating the day of the week.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?