Check if a Date is Before Another Date in Python

This tutorial will discuss about a unique way to check if a date is before another date in Python.

Suppose we have two dates in the string format,

date1 = '2023-04-12'
date2 = '2023-05-22'

Now we want to check if date1 is before date2. We have created a method for it,

from datetime import datetime

def is_before_date(dateStr1, dateStr2):
    # Checks if dateStr1 is before dateStr2.
    # Returns True if dateStr1 is before dateStr2, False otherwise.
    date1 = datetime.strptime(dateStr1, '%Y-%m-%d').date()
    date2 = datetime.strptime(dateStr2, '%Y-%m-%d').date()
    return date1 < date2

It accepts the 2 dates in string format and turns True if dateStr1 is before dateStr2, otherwise it returns False.

Inside the function, it first converts the date from string format to date object. Then it uses < operator to check if the date1 is less than date2.

Let’s see the complete example,

from datetime import datetime

def is_before_date(dateStr1, dateStr2):
    # Checks if dateStr1 is before dateStr2.
    # Returns True if dateStr1 is before dateStr2, False otherwise.
    date1 = datetime.strptime(dateStr1, '%Y-%m-%d').date()
    date2 = datetime.strptime(dateStr2, '%Y-%m-%d').date()
    return date1 < date2

# Example usage:
dateStr1 = '2023-04-12'
dateStr2 = '2023-05-22'

if is_before_date(dateStr1, dateStr2):
    print('Yes, date1 is before date2')
else:
    print('no, date1 is not before date2')

Output

Yes, date1 is before date2

Summary

We learned how to check if a Date is Before Another Date in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top