14

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."
3
  • 1
    You should use YYYY-MM-DD format unless you want 27-11 to be before 28-10 Commented Nov 29, 2017 at 4:36
  • Also, why are you not just comparing datetime objects? Commented Nov 29, 2017 at 4:37
  • Like @cricket_007 said, this isn't the right way to do this. Much safer (and more accurate in general) to compare datetime objects. Commented Nov 29, 2017 at 4:38

1 Answer 1

29

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Alright, now i see my error i'll keep that in mind in the future...Thank you so much, i really appreciate it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.