Get the date n days ago and n days after in Python

Few day’s ago I found a helpful method to get n day’s ago date and n days after date from current date. Following functions are written based on Python 3.

Date n day’s ago:


from datetime import datetime, timedelta

def get_n_days_before_date(date_format="%d %B %Y", days_before=120):

    date_n_days_ago = datetime.now() - timedelta(days=days_before)
    return date_n_days_ago.strftime(date_format)

Date n day’s after:

from datetime import datetime, timedelta

def get_n_days_after_date(date_format="%d %B %Y", add_days=120):

    date_n_days_after = datetime.now() + timedelta(days=add_days)
    return date_n_days_after.strftime(date_format)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s