Introduction
In Python, you can use the datetime module to work with dates and times. One common task is to check if a given date is a weekday or a weekend. In this challenge, you will write a function that takes a date as input and returns True if it is a weekday, and False if it is a weekend.
Check if a Date is a Weekday
Write a Python function called is_weekday() that takes a date as input and returns True if it is a weekday, and False if it is a weekend. If no date is provided, the function should use the current date.
To solve this problem, you can follow these steps:
- Import the
datetimemodule. - Define a function called
is_weekday()that takes a date as input. If no date is provided, use the current date. - Use the
weekday()method of thedatetimemodule to get the day of the week as an integer. Theweekday()method returns an integer between 0 (Monday) and 6 (Sunday). - Check if the day of the week is less than or equal to 4. If it is, return
True, otherwise returnFalse.
from datetime import datetime
def is_weekday(d = datetime.today()):
return d.weekday() <= 4
from datetime import date
is_weekday(date(2020, 10, 25)) ## False
is_weekday(date(2020, 10, 28)) ## True
Summary
In this challenge, you learned how to use the datetime module to check if a given date is a weekday or a weekend. You also practiced defining functions and using conditional statements in Python.