How to Get Day of Week in Python: Simple Examples
Use the
datetime module in Python to get the day of the week. You can call datetime.datetime.today().weekday() to get the day as a number (0=Monday), or use strftime('%A') to get the full day name as a string.Syntax
To get the day of the week in Python, use the datetime module. The main methods are:
datetime.datetime.today().weekday(): returns an integer from 0 (Monday) to 6 (Sunday).datetime.datetime.today().strftime('%A'): returns the full weekday name as a string, like 'Monday'.
python
import datetime # Get weekday as number (0=Monday, 6=Sunday) weekday_number = datetime.datetime.today().weekday() # Get weekday as full name string weekday_name = datetime.datetime.today().strftime('%A')
Example
This example shows how to print both the weekday number and the weekday name for today's date.
python
import datetime # Get today's date today = datetime.datetime.today() # Get weekday number (0=Monday) weekday_num = today.weekday() # Get weekday name weekday_str = today.strftime('%A') print(f"Weekday number: {weekday_num}") print(f"Weekday name: {weekday_str}")
Output
Weekday number: 3
Weekday name: Thursday
Common Pitfalls
One common mistake is confusing weekday() and isoweekday(). weekday() counts Monday as 0, Sunday as 6, while isoweekday() counts Monday as 1, Sunday as 7.
Also, using strftime('%w') returns Sunday as 0, which can be confusing.
python
import datetime today = datetime.datetime.today() # Wrong: assuming Sunday is 7 with weekday() wrong_day = today.weekday() # Sunday is 6 here # Right: use isoweekday() if you want Monday=1, Sunday=7 right_day = today.isoweekday() print(f"weekday() gives: {wrong_day}") print(f"isoweekday() gives: {right_day}")
Output
weekday() gives: 3
isoweekday() gives: 4
Quick Reference
| Method | Returns | Value Range | Notes |
|---|---|---|---|
datetime.datetime.today().weekday() | Weekday number | 0 (Monday) to 6 (Sunday) | Commonly used, zero-based index |
datetime.datetime.today().isoweekday() | Weekday number | 1 (Monday) to 7 (Sunday) | ISO standard numbering |
datetime.datetime.today().strftime('%A') | Weekday name | String like 'Monday' | Full weekday name |
datetime.datetime.today().strftime('%a') | Weekday abbreviation | String like 'Mon' | Short weekday name |
Key Takeaways
Use datetime.today().weekday() to get the day of week as a number from 0 (Monday) to 6 (Sunday).
Use datetime.today().strftime('%A') to get the full weekday name as a string.
Remember weekday() starts counting at 0 for Monday, while isoweekday() starts at 1 for Monday.
Avoid confusion by choosing the method that fits your numbering preference.
strftime() formatting codes like '%A' and '%a' help get readable day names.