求两个日期之间间隔的天数,Python实现

自己写的方法,求出第一年到倒数第二年里一共所有天数,然后减去第一年里日期前的天数,加上最后一年里日期前的天数。代码:

 1 def leap_year(y):   #判断是否是闰年
 2     if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
 3         return True
 4     else:
 5         return False
 6         
 7 def days_in_month(y, m):    #判断每个月都有几天
 8     if m in [1, 3, 5, 7, 8, 10, 12]:
 9         return 31
10     elif m in [4, 6, 9, 11]:
11         return 30
12     else:
13         if leap_year(y):
14             return 29
15         else:
16             return 28
17             
18 def days_this_year(year):   #判断今年共几天
19     if leap_year(year):
20         return 366
21     else:
22         return 365
23             
24 def days_passed(year, month, day):  #判断今年过了几天
25     m = 1
26     days = 0
27     while m < month:
28         days += days_in_month(year, m)
29         m += 1
30     return days + day
31 
32 def daysBetweenDates(year1, month1, day1, year2, month2, day2):
33     ##
34     # Your code here.
35     ##
36     if year1 == year2:
37         return days_passed(year2, month2, day2) - days_passed(year1, month1, day1)
38     else:
39         sum1 = 0
40         y1 = year1
41         while y1 < year2:
42             sum1 += days_this_year(y1)
43             y1 += 1
44         return sum1-days_passed(year1,month1,day1)+days_passed(year2,month2,day2)

 

用下面的代码进行正确性测试

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

 

测试结果如下

Udacity上的老师David Evans(University of Virginia)演示的方法,更清晰:

# Credit goes to Websten from forums
#
# Use Dave's suggestions to finish your daysBetweenDates
# procedure. It will need to take into account leap years
# in addition to the correct number of days in each month.

def isLeapYear(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def daysInMonth(year, month):
    if month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    elif month in [4, 6, 9, 11]:
        return 30
    else:
        if isLeapYear(year):
            return 29
        else:
            return 28

def nextDay(year, month, day):
    """Simple version: assume every month has 30 days"""
    if day < daysInMonth(year, month):
        return year, month, day + 1
    else:
        if month == 12:
            return year + 1, 1, 1
        else:
            return year, month + 1, 1
        
def dateIsBefore(year1, month1, day1, year2, month2, day2):
    """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
    if year1 < year2:
        return True
    if year1 == year2:
        if month1 < month2:
            return True
        if month1 == month2:
            return day1 < day2
    return False

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    """Returns the number of days between year1/month1/day1
       and year2/month2/day2. Assumes inputs are valid dates
       in Gregorian calendar."""
    # program defensively! Add an assertion if the input is not valid!
    assert not dateIsBefore(year2, month2, day2, year1, month1, day1)
    days = 0
    while dateIsBefore(year1, month1, day1, year2, month2, day2):
        year1, month1, day1 = nextDay(year1, month1, day1)
        days += 1
    return days

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]
    
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

 

posted @ 2014-08-18 01:45  jk123vip  阅读(4982)  评论(0编辑  收藏  举报