Checking date against date range in Python

Subtracting two date objects gives you a timedelta object, which you can compare to other timedelta objects.

For example:

>>> from datetime import date, timedelta
>>> date(2011, 1, 15) - date.today()
datetime.timedelta(1)
>>> date(2011, 1, 15) - date.today() < timedelta(days = 3)
True
>>> date(2011, 1, 18) - date.today() < timedelta(days = 3)
False

As to "where to look": the official documentation is excellent.


Object oriented solution

import datetime

class DatetimeRange:
    def __init__(self, dt1, dt2):
        self._dt1 = dt1
        self._dt2 = dt2

    def __contains__(self, dt):
        return self._dt1 < dt < self._dt2

dt1 = datetime.datetime.now()
dt2 = dt1 + datetime.timedelta(days = 2)
test_true = dt1 + datetime.timedelta(days = 1)
test_false = dt1 + datetime.timedelta(days = 5)

test_true in DatetimeRange(dt1, dt2) #Returns True
test_false in DatetimeRange(dt1, dt2) #Returns False

In Python to check a range you can use a <= x <= b:

>>> import datetime
>>> today = datetime.date.today()
>>> margin = datetime.timedelta(days = 3)

>>> today - margin <= datetime.date(2011, 1, 15) <= today + margin
True