假设我有两个由字符串表示的日期。MM-DD-YY
在 Python 中找出哪个日期最先出现的最有效方法是什么?我尝试了以下方法,但很快就变得一团糟!
我正在寻找以下输出:return 1 if first date comes before, 0 if second date comes before, -1 if dates are exactly the same
希望有人有更清洁的方法
date1 = "02-20-10"
date2 = "03-21-09"
def firstDateBefore(date1, date2):
month1, day1, year1 = date1.split("-")
month2, day2, year2 = date2.split("-")
month1 = int(month1)
month2 = int(month2)
day1 = int(day1)
day2 = int(day2)
year1 = int(year1)
year2 = int(year2)
if (year1 < 13 && year2 < 13): #both in the year 2000's
if (year1 < year2):
return 1
else if (year1 > year2):
return 0;
else: #years are equal
if (month1 < month2):
return 1
else if (month1 > month2):
return 0
else: #months are equal
if (day1 < day2):
return 1
else if (day1 > day2):
return 0
else
return -1 # the Dates are exactly the same!