Check If Date is Within 7 Days in Python

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

Many times we encounter a scenario where a date is given, and we want to check if the given date is within the last 7 days or not.

We have created a generic method to check if given date is within last N days or not,

from datetime import datetime, timedelta

def is_within_last_N_days(dateStr, N):
    # Checks if dateStr is within last N days.
    # Returns True, if dateStr is within last N days, False otherwise.
    today = datetime.today().date()
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()

    return (today - timedelta(days=N)) <= dateObj <= today

It accepts a date in string format as first argument, and an integer value N as the second argument.

It converts the date from string to date type of datetime module, using the strptime() method. Then it creates a date object pointing to today’s date. After that, it subtracts N days from today’s date to create a start Date. Then checks if the given date is within start date and today’s date. If yes, then it returns True, otherwise it returns False. Basically it converts the dates from string format to date object and then checks if the date is within last N days or not.

In the below example, we will check if a date i.e. ‘2023-04-23’ is within last 7 days or not.

Let’s see the complete example,

from datetime import datetime, timedelta

def is_within_last_N_days(dateStr, N):
    # Checks if dateStr is within last N days.
    # Returns True, if dateStr is within last N days, False otherwise.
    today = datetime.today().date()
    dateObj = datetime.strptime(dateStr, '%Y-%m-%d').date()

    return (today - timedelta(days=N)) <= dateObj <= today

dateStr = '2023-04-23'

# Check if given date is within last 7 days
if is_within_last_N_days(dateStr, 7):
    print('Yes, dateStr is within last 7 days')
else:
    print('No, dateStr is not within last 7 days')

Output

Yes, dateStr is within last 7 days

Summary

We learned how to check if a date is within last 7 days or not 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