Check if Date is Today in Python

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

When we are developing an application, many times we encounter a scenario where we need to take certain decision or perform certain operations on a particular date only. For this we need a code to compare dates. Today we will learn about a scenario, where we need to check a given date in string format is today’s date or not.

Suppose we have a date in the string format like this,

dateStr = '2023-04-27'

Now we want to check if this date is today’s date or not. For that, first we will convert this string format date into the date object, from the datetime module. Then we will create another date object, that points to the current date or today’s date. After that we can compare the given date and today’s date to check if actually the given date is today’s date or not. We have created a separate function for this,

from datetime import datetime

def is_today(dateStr):
    # Checks if a given date is today.
    # Returns True if the date is today, False otherwise.
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()
    today = datetime.now().date()
    return dateObj == today

In this method, we can pass a date in the string format. It will return True, if the given date is today’s date otherwise it will return false.

Let’s see the complete example,

from datetime import datetime

def is_today(dateStr):
    # Checks if a given date is today.
    # Returns True if the date is today, False otherwise.
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()
    today = datetime.now().date()
    return dateObj == today

dateStr = '2023-04-27'
if is_today(dateStr):
    print("Yes, its Today's Date")
else:
    print("No, its not Today's Date")

Output

Yes, its Today's Date

Summary

We learned how to check if a give date in string is today’s date or not.

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