how to infer weekday names based on date in python

You can use the date.weekday() method to get the weekday index (0 for Monday, 1 for Tuesday,..., 6 for Sunday). Then you can use a dictionary to map the index to the corresponding weekday name.

Here's an example code:

main.py
from datetime import date

# create a date object
my_date = date(2021, 9, 22)

# get the weekday index (0 for Monday, 1 for Tuesday,..., 6 for Sunday)
weekday_index = my_date.weekday()

# map the index to the corresponding weekday name
weekday_names = {
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday'
}

weekday_name = weekday_names[weekday_index]

print(weekday_name)  # output: 'Wednesday'
471 chars
23 lines

Alternatively, you can use the date.strftime() method to format the date as a string with the weekday name. Here's an example:

main.py
from datetime import date

# create a date object
my_date = date(2021, 9, 22)

# format the date string with the weekday name (%A)
weekday_name = my_date.strftime('%A')

print(weekday_name)  # output: 'Wednesday'
213 chars
10 lines

Note that both methods assume that Monday is the first day of the week. If you want to use a different start day, you'll need to adjust the weekday index accordingly.

related categories

gistlibby LogSnag