How can I get the day of the week given a date in Python?
I want to determine the corresponding day of the week for a given date (as a datetime
object). For instance, Sunday is the first day, Monday is the second day, and so on. How can I implement this?
For example, if today’s date is passed in:
>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday() # what I'm looking for
The output might be 6
since it’s Friday.
How can I implement this in Python for day of week?
The weekday() method returns an integer where Monday is 0 and Sunday is 6. This can be used to get the day of the week.
import datetime
today = datetime.datetime(2017, 10, 20)
day_of_week = today.weekday() # Returns 4 (Friday)
print(day_of_week)
The calendar module also provides a weekday() function that behaves similarly to datetime.weekday(). It returns the day of the week as an integer, with Monday being 0 and Sunday being 6.
import calendar
import datetime
today = datetime.datetime(2017, 10, 20)
day_of_week = calendar.weekday(today.year, today.month, today.day) # Returns 4 (Friday)
print(day_of_week)
If you’d like the name of the day instead of the number, you can use the strftime() method to format the date as a string representing the day of the week.
import datetime
today = datetime.datetime(2017, 10, 20)
day_of_week = today.strftime('%A') # Returns 'Friday'
print(day_of_week)