Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 825
widget Avatar asked Mar 28 '11 20:03

widget


2 Answers

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

if start <= date <= end:
    print("in between")
else:
    print("No!")
like image 148
Björn Pollex Avatar answered Nov 07 '22 20:11

Björn Pollex


As you are still not satisfied, I have another answer for you. Without using datetime and year.

It just uses built-in tuples and comparing them:

d1 = (3, 28)
d2 = (3, 31)
d3 = (4, 2)
if d1 < d2 < d3:
    print("BETWEEN!")
else:
    print("NOT!")

You can create tuple like these easily:

day = 16
month = 4
d = (month, day)
like image 53
Maciej Ziarko Avatar answered Nov 07 '22 22:11

Maciej Ziarko