This tutorial will discuss about a unique way to check if date is older than 30 days in Python.
Suppose we have a date in string format like this,
dateStr = '2023-02-16'
Now we want to check if this date is older than the 30 days or not.
We have created a generic function which accepts a date string as first argument and a number N is the second argument. Where N is the number of days. This method returns True if the given date is older than the N days.
from datetime import datetime, date, timedelta # Returns True, if the given date is older than N Days def is_older_than_N_days(dateStr, N): # Create a date object for the current date today = date.today() # Create a date object from string format of date dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date() # Create a date object for the date N days ago startDate = today - timedelta(days=N) # check if the given date is older than N days if dateObj < startDate: return True else: return False
In this method, first we will fetch today’s date as a date object and then we will convert the given date from string format to the date object of datetime module. Then we will substract N days from today’s date that will give us a starting date. After that compare the given date object with the starting date, if it is less than the starting date then that means the given date is older than N days
To Check if Date is Older than 30 Days, we can call this function with the date string as the first argument and 30 is the second argument. It will return true if the date is older than 30 days.
Like here, in the below example date is of 16th February and today’s date is 26th April 2023. So the given date is older than the 30 days from today’s date
Frequently Asked:
Let’s see the complete example,
from datetime import datetime, date, timedelta # Returns True, if the given date is older than N Days def is_older_than_N_days(dateStr, N): # Create a date object for the current date today = date.today() # Create a date object from string format of date dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date() # Create a date object for the date N days ago startDate = today - timedelta(days=N) # check if the given date is older than N days if dateObj < startDate: return True else: return False dateStr = '2023-02-16' # check if given date is older than 30 days if is_older_than_N_days(dateStr, 30): print("Yes, Date is Older than 30 Days") else: print("No, Date is not Older than 30 Days")
Output
Yes, Date is Older than 30 Days
Summary
We learned a way to check if a Date is Older than 30 Days in Python.