3

I need help with the python function of comparing two dates (string) and return True if date1 is ealier than date2. Here is my code but I'm don't know why it returns True for the test case("2013/10/24", "2013/9/24")

# str, str -> boolean
def dateLessThan(date1,date2):
   date1 = date1.split('/')
   date2 = date2.split('/')
   if date1[0] < date2[0]:
      return True
   elif date1[0] == date2[0] and date1[1] < date2[1]:
      return True
   elif date1[0] == date2[0] and date1[1] == date2[1] and date1[2] < date2[2]:
      return True
   else:
      return False
3
  • lexicographic comparison, that's why. "10" < "9" Commented Oct 26, 2017 at 20:54
  • Hint: 10 is greater than 9, but '9' is greater than '10'. Commented Oct 26, 2017 at 20:54
  • Use ISO-8601 date formats, and you don't have to parse them at all; their lexicographical ordering with match their chronological ordering. Commented Oct 26, 2017 at 21:04

3 Answers 3

4

Just use the datetime.strptime class method instead of doing your own parsing.

def dateLessThan(date1,date2):
   date1 = datetime.datetime.strptime(date1, "%Y/%m/%d")
   date2 = datetime.datetime.strptime(date2, "%Y/%m/%d")
   return date1 < date2
Sign up to request clarification or add additional context in comments.

Comments

2

Consider using datetime objects (assumed your time format is YY/mm/dd)

from datetime import datetime

def dateLessThan(date1,date2):
   datetime1 = datetime.strptime(date1, '%Y/%m/%d')
   datetime2 = datetime.strptime(date2, '%Y/%m/%d')
   return datetime1 < datetime2

Comments

1

your test fails because of lexicographical comparison of strings. "10" < "9".

Without using datetime or time parsing (which is required when there are complex formats, months names...), it's possible to do something simple since there's only numbers involved (and you have years/month/day, so you're close to the ISO date format where you can compare lexicographically).

Just map the values into integers and convert to lists and let the natural/lexicographical order of lists do the rest:

def dateLessThan(date1,date2):
   return [int(x) for x in date1.split('/')] < [int(x) for x in date2.split('/')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.