In this tutorial, we will demonstrate how to check if today is Monday using Python. Learning this technique can be helpful when creating applications that involve logging dates, organizing workflow, or facilitating reminders, among others.
Step 1: Import the necessary libraries
Begin by importing the datetime library, which provides numerous functions and classes for managing dates, times, and time intervals.
1 |
import datetime |
Step 2: Get the current date
Next, retrieve the current date using the date.today() method from the datetime library. This method returns the current local date, expressed as a date object.
1 |
current_date = datetime.date.today() |
Step 3: Check if today is Monday
To determine whether it’s Monday, use the weekday() method on the date object. This method returns an integer representing the day of the week, with Monday represented by 0, and Sunday by 6.
1 |
is_monday = current_date.weekday() == 0 |
After obtaining the result, print it.
1 |
print("Is today Monday?", is_monday) |
Full code
Here’s the complete code:
1 2 3 4 5 |
import datetime current_date = datetime.date.today() is_monday = current_date.weekday() == 0 print("Is today Monday?", is_monday) |
Output
Is today Monday? True
Note that the output value will be True if it’s Monday, and False otherwise.
Conclusion
In this tutorial, we learned how to check if today is Monday in Python using the datetime library. This can be easily adapted to check for other days of the week by changing the integer value in the comparison. For example, you can check if it’s Wednesday by using current_date.weekday() == 2 instead.