This tutorial will discuss about a unique way to check if date is weekday in Python.
Suppose you have a date in the string format like this,
dateStr = '2023-04-26'
Now you want to check if these state is today’s date or not in Python.
Python provides a module datetime
to handle the date and time stuff. We are going to use two classes from this module i.e. datetime and date. We have created a separate function for this,
from datetime import datetime, date def is_weekday(dateStr): # Create a date object from string format of date dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date() # Check if the given date is a weekday # (i.e., not a Saturday or Sunday) if dateObj.weekday() < 5: return True else: return False
It accepts a date in string format, and returns True, if the given date is a weekday otherwise it returns False.
Internal Details:
As we have a date in string format, so first we need to convert this string into it date object and we are going to do that using the datetime.strptime()
method of the datetime module.
Frequently Asked:
- Convert Local datetime to UTC timezone in Python
- Python: Get list of all timezones in pytz module
- Python: Get difference between two datetimes in microseconds
- Add hours to current time in Python
In strptime() method, pass the date string as the first argument, and as second argument pass the format in which the string contains the date. It will give us a datetime object populated with the given date. Then call the date() method on that datetime object to get a date object.
The date object has a method weekday()
, which returns a number representing the day of the week, which this current date object is pointing to. If it is Monday, then it will return 0, if it is Tuesday then it will return 1. Similarly if it is Saturday or Sunday then it will return 5 or 6 respectively. Use this method to check if the return value is less than 5 or not. If yes, then it means the given date is a weekday.
Let’s see the complete example,
from datetime import datetime, date def is_weekday(dateStr): # Create a date object from string format of date dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date() # Check if the given date is a weekday # (i.e., not a Saturday or Sunday) if dateObj.weekday() < 5: return True else: return False dateStr = '2023-04-26' # Check If Date is Weekday # i.e. not Saturday or Sunday if is_weekday(dateStr): print("Yes, Date is Weekday") else: print("No, Date is not Weekday")
Output
Yes, Date is Weekday
Summary
We learned a way to check if a given Date is a weekday in Python.