我正在尝试检查今天的日期(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."
答案 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)