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

泄露秘密 提交于 2019-12-17 10:36:15

问题


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. Thanks for any help!


回答1:


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)



回答2:


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

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



回答3:


Use datetime.date:

http://docs.python.org/library/datetime.html#datetime.date

< operator is overloaded specially for you.

date1 < date2 - date1 is considered less than date2 when date1 precedes date2 in time.

>>> from datetime import date
>>> d1 = date(2011, 3, 28)
>>> d2 = date(2011, 3, 22)
>>> d3 = date(2011, 4, 3)
>>> d2 < d1 < d3
True

Or in your prgram:

from datetime import date

d1 = date(2011, 3, 28)
d2 = date(2011, 3, 22)
d3 = date(2011, 4, 3)

if d2 < d1 < d3:
    print 'in between'
else:
    print 'No!'



回答4:


from datetime import datetime

date_format = "%m/%d/%Y"

a = datetime.strptime('8/18/2008', date_format)

b = datetime.strptime('9/26/2007', date_format) # Date to be checked

c = datetime.strptime('9/25/2008', date_format)

d = datetime.strptime('8/18/2008', date_format)  #Date entered here should always be the same as 'a'

delta1 = b - a

delta2 = c - b

delta3 = d - a

if delta1.days >= delta3.days and delta2.days >= delta3.days:

    print 'In between'

else:

    print 'Not in between'


来源:https://stackoverflow.com/questions/5464410/how-to-tell-if-a-date-is-between-two-other-dates-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!