如何检查Python上的日期是否在范围内?

时间:2017-11-29 04:33:22

标签: python python-2.7 datetime python-datetime

我正在尝试检查今天的日期(dd-mm-yyyy格式)是否在给定范围内。

我的代码只检查当天,而不是月份或年份......你能帮我看看有什么不对吗?

这里工作正常......

import datetime
TODAY_CHECK = datetime.datetime.now()
TODAY_RESULT = ('%s-%s-%s' % (TODAY_CHECK.day, TODAY_CHECK.month, TODAY_CHECK.year))
if '26-11-2017' <= TODAY_RESULT <= '30-11-2017':
    print "PASS!"
else:
    print "YOU SHALL NOT PASS, FRODO."

但这里没有......

import datetime
TODAY_CHECK = datetime.datetime.now()
TODAY_RESULT = ('%s-%s-%s' % (TODAY_CHECK.day, TODAY_CHECK.month, TODAY_CHECK.year))
if '26-11-2017' <= TODAY_RESULT <= '01-12-2017':
    print "PASS!"
else:
    print "YOU SHALL NOT PASS, FRODO."

1 个答案:

答案 0 :(得分:1)

您正在比较字符串。您应该比较日期时间/日期对象

import datetime
TODAY_CHECK = datetime.datetime.now()
start = datetime.datetime.strptime("26-11-2017", "%d-%m-%Y")
end = datetime.datetime.strptime("30-11-2017", "%d-%m-%Y")
if start <= TODAY_CHECK <= end:
    print "PASS!"
else:
    print "YOU SHALL NOT PASS, FRODO."

或者你可以做

start = datetime.datetime(day=26,month=11,year=2017)
end = datetime.datetime(day=30,month=11,year=2017)