user2294401
user2294401

Reputation: 387

How can i find if the date lies between two dates

I have the date like

date['min'] = '2013-11-11'
date['max'] = '2013-11-23'

Is there any single line function which can return true if date lies in that range.

I mean if only date.min is provided then i need to check if given date is grater than it and if only max is provided then i need to check if its less than that. and if both are provided then whether it falls between them

Upvotes: 3

Views: 8473

Answers (3)

eumiro
eumiro

Reputation: 212825

Dates in the form YYYY-MM-DD can be compared alphabetically as well:

'2013-11-11' < '2013-11-15' < '2013-11-23'

date['min'] < your_date < date['max']

This won't work correctly for other formats, such as DD.MM.YYYY or MM/DD/YYYY. In that case you have to parse the strings and convert them into datetime objects.

If don't know whether the min/max variables are present, you can do:

date.get('min', '0000-00-00') < your_date < date.get('max', '9999-99-99')

and replace the default text values with anything you prefer.

Upvotes: 9

Asterisk
Asterisk

Reputation: 3574

I think simple comparison works for that.

>>> from datetime import timedelta, date
>>> min_date = date.today()
>>> max_date = date.today() + timedelta(days=7)
>>> d1 = date.today() + timedelta(days=1)
>>> d2 = date.today() + timedelta(days=10)
>>> min_date < d1 < max_date
True
>>> min_date < d2 < max_date
False

Here is the updated version:

def is_in_range(d, min=date.min, max=date.max):
    if max:
        return min < d < max
    return min < d


print is_in_range(d1, min_date, max_date)
print is_in_range(d2, min_date, max_date)
print is_in_range(d1, min_date)
print is_in_range(d2, min_date)

True
False
True
True

Upvotes: 2

Don
Don

Reputation: 17606

If you deal with date objects:

from datetime import date
in_range = (first_date or date.min) < my_date < (second_date or date.max)

Upvotes: 1

Related Questions