如何在Python上检查日期是否在范围内?
问题描述:
我正在尝试检查今天的日期(格式为 dd-mm-yyyy
)是否在给定范围内。
I'm trying to check if today's date (in dd-mm-yyyy
format) is in a given range.
我的代码仅检查日期,而不检查月份或年份...您能帮我看看问题是什么吗?
My code only checks the day, not the month or year... Could you help me to see what's wrong?
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."
但是这里没有...
But here it doesn't...
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."
答
您正在比较字符串。您应该比较日期时间/日期对象
You are comparing strings. You should compare datetime/date objects
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)