How can i check if date is on range on Python? [duplicate]

女生的网名这么多〃 提交于 2019-12-13 02:42:44

问题


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?

Here it works fine...

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."

回答1:


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."

or you can do

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


来源:https://stackoverflow.com/questions/47545090/how-can-i-check-if-date-is-on-range-on-python

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