Python检查两个字符串日期的早期

时间:2013-10-22 06:40:49

标签: python string date

假设我有两个由字符串表示的日期。 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!

2 个答案:

答案 0 :(得分:3)

Python comes with batteries included

from datetime import datetime

d1 = datetime.strptime(date1, "%m-%d-%y")
d2 = datetime.strptime(date2, "%m-%d-%y")

assert d1 > d2

What "%m-%d-%y" means.

答案 1 :(得分:0)

您可以将日期转换为时间戳以快速比较:

from datetime import datetime

def firstDateBefore(date1, date2):
    d1 = datetime.datetime.strptime(date1, '%m-%d-%y').strftime('%s')
    d2 = datetime.datetime.strptime(date2, '%m-%d-%y').strftime('%s')
    if d1 > d2:
        return d1
    elif d1 == d2:
        return 'same date'
    else:
        return D2

如果日期相等,这个例子会返回更大的日期或“同一日期”......