from datetime import date
dt = date.today()
print(dt.isoweekday())
Output
2
Using date and time object
from datetime import datetime
dt = datetime(2019, 12, 31)
print(dt.isoweekday())
Output
2
Example with weekday()
from datetime import date
dt = date.today()
print(dt.weekday()) # Monday = 0
print(dt.isoweekday()) # Monday = 1
from datetime import date
dt = date(2024, 9, 14)
if dt.isoweekday() in [6, 7]:
print(f"{dt} is a weekend.")
else:
print(f"{dt} is a weekday.")
Output
2024-09-14 is a weekend.
from datetime import date, timedelta
today = date.today()
for i in range(7):
future_date = today + timedelta(days=i)
print(future_date, future_date.isoweekday())
Output
2024-09-14 6
2024-09-15 7
2024-09-16 1
2024-09-17 2
2024-09-18 3
2024-09-19 4
2024-09-20 5
We can generate a list of all Mondays in a specific month using isoweekday().
from datetime import date, timedelta
def get_weekdays_in_month(year, month, weekday):
# weekday: 1=Monday, 2=Tuesday, ..., 7=Sunday
dates_list = []
current_date = date(year, month, 1)
while current_date.month == month:
if current_date.isoweekday() == weekday:
dates_list.append(current_date)
current_date += timedelta(days=1)
return dates_list
mondays_in_february_2025 = get_weekdays_in_month(2025, 2, 1)
for monday in mondays_in_february_2025:
print(monday)
The difference between isoweekday() and weekday() is in their numbering system. The isoweekday() method returns 1 for Monday through 7 for Sunday, whereas weekday() returns 0 for Monday through 6 for Sunday.
from datetime import date
dt = date(2025, 2, 9) # February 9, 2025
print(f"weekday(): {dt.weekday()}") # Output: 6
print(f"isoweekday(): {dt.isoweekday()}") # Output: 7
We can use isoweekday() to check the current day and execute corresponding tasks in an application where specific tasks run on particular days.
from datetime import date
today = date.today()
if today.isoweekday() == 1: # Monday
print("Execute Monday's tasks.")
elif today.isoweekday() == 5: # Friday
print("Prepare for the weekend.")
else:
print("Continue with the usual workflow.")
The isoweekday() method is a simple yet powerful tool for handling date-related logic, especially in scheduling and reporting applications. By leveraging this method, we can efficiently classify days, generate date-based reports, and automate tasks based on the day of the week.
2nd Saturday | Display 2nd and 4th Saturday of the month |
calendar | Calendar module to Create yearly or monthly Calendars |