How to tell if a date is between two other dates?

widget picture widget · Mar 28, 2011 · Viewed 75.1k times · Source

I have the following codes:

if date in (start, end):
        print 'in between'
else:
        print 'No!'

date, start and end are all variables with the format of 1/1. What should I do to have it print out the right result? i tried date as 10/2, start as 3/14 and end as 11/7 and it's print 'No!', which means it's not running right. I guess have to format them to a date format and then compare them.

Answer

Björn Pollex picture Björn Pollex · Mar 28, 2011

If you convert all your dates to datetime.date, you can write the following:

if start <= date <= end:
    print "in between"
else:
    print "No!"