user8840209
user8840209

Reputation:

Comparing Dates string in Python

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

Upvotes: 3

Views: 3971

Answers (3)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

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('/')]

Upvotes: 1

chepner
chepner

Reputation: 530872

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

Upvotes: 4

knowa42
knowa42

Reputation: 404

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

Upvotes: 2

Related Questions