Python Language Date and Time Computing time differences

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


the timedelta module comes in handy to compute differences between times:

from datetime import datetime, timedelta
now =
then = datetime(2016, 5, 23)     # datetime.datetime(2016, 05, 23, 0, 0, 0)

Specifying time is optional when creating a new datetime object

delta = now-then

delta is of type timedelta

# 60
# 40826

To get n day's after and n day's before date we could use :

n day's after date:

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

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

n day's before date:

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

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

Got any Python Language Question?