在Python中计算日期之间的天数?

时间:2019-03-18 02:39:22

标签: python

为此设置了一些课程作业。一切都很好,直到我发现其中一个测试用例无法正常工作,试图使2012-1-12013-1-1之间的间隔时间达到为止。

我猜应该是366天,因为2012是a年。这段代码似乎在猜测365,我的导师将答案标记为360。

他说了一些“只赚30个月”,所以我想他的360与此有关吗?无论如何,当我猜代码为365时,这并不能为我的代码猜测366辩解。

输出如图所示

  

测试用例通过!祝贺
  使用数据进行测试:(2012、1、1、2013、1、1)未能通过365,应该通过360
  测试用例通过!祝贺

daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 

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

def get_days_from_year(year):
    days = year * 365
    i = 0

    while i < year:
        i += 1
        if is_leap_year(i):
            days += 1

    return days

def get_days_from_month(month, year):
    days = 0
    i = 0

    while i < month:
        if i == 1 and is_leap_year(year):
            days += daysOfMonths[i] + 1
        else:
            days += daysOfMonths[i]
        i += 1

    return days

def get_days_from_date(year, month, day): 
    days_in_year = get_days_from_year(year)
    days_in_month = get_days_from_month(month - 1, year)
    days = days_in_year + days_in_month + day
    return days

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    first_date_days = get_days_from_date(year1, month1, day1)
    second_date_days = get_days_from_date(year2, month2, day2)


    if first_date_days > second_date_days:
        return first_date_days - second_date_days
    else:
        return second_date_days - first_date_days

def test():
    test_cases = [((2012,9,30,2012,10,30),30), 
                  ((2012,1,1,2013,1,1),360),
                  ((2012,9,1,2012,9,4),3)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print("Test with data:", args, "failed passed", result, "should of passed", answer)
        else:
            print("Test case passed! CONGRATULATIONS")

test()

2 个答案:

答案 0 :(得分:0)

您在错误的位置递增了 i 。你有:

while i < year:
    i += 1
    if is_leap_year(i):
        days += 1

但应为:

while i < year:
    if is_leap_year(i):
        days += 1
    i += 1

因此,您的leap年都减少了1(2011年与2012年,2015年与2016年等)

答案 1 :(得分:0)

他说了一些有关“ 让整个月都变成30天” ,所以

def get_range(year1,month1,day1,year2,month2,day2):
    """
    assumes all months have 30 days, with no leap years
    ~ for some weird reason i dont understand
   (probably so you dont use builtin datetime)

    """
    days_difference = (year2-year1)*360
    days_difference += (month2-month1)*30
    return days_difference + day2-day1


print(get_range(2012, 1, 1, 2013, 1, 1))

如果要获取两个日期之间的实际天数

from datetime import datetime
def get_real_range(year1,month1,day1,year2,month2,day2):
    return (datetime(year2,month2,day2) - datetime(year1,month1,day1)).days
相关问题