Python在一个月内输出0天

时间:2018-02-08 22:17:10

标签: python datetime

当我运行它时,输出总是0,我期待29或30。

import datetime

def days_in_month(year, month):
    """
    Inputs:
      year  - an integer between datetime.MINYEAR and datetime.MAXYEAR
              representing the year
      month - an integer between 1 and 12 representing the month

    Returns:
      The number of days in the input month.
    """

    #if month is december, we proceed to next year
    def month_december(month):
        if month == 12:
            return 1
        else:
            return month

    #if month is december, we proceed to next year
    def year_december(year, month):
        if month == 12:
            return new_year + 1
        else:
            return year

    #verify if month/year is valid
    if (month < 1) or (month > 12):
        print ("please enter a valid month")
    elif (year < 1) or (year > 9999):
        print ("please enter a valid year between 1 - 9999")
    else:
        #subtract current month from next month then get days
        date1 = (datetime.date(year_december(year, month), month_december(month), 1) - datetime.date(year, month, 1)).days
        print (date1)

days_in_month(1997, 1)

2 个答案:

答案 0 :(得分:1)

正如丹尼尔所说,有一种标准的库方法。重复使用总是比重新发明更好。

*ngIf

答案 1 :(得分:0)

您忘了在第一个参数添加一个月。 你的代码:

datetime.date(year_december(year, month), month_december(month), 1)
= datetime.date(year, month, 1)

新代码:

date1 = (datetime.date(year_december(year, month+1), month_december(month+1), 1) - datetime.date(year, month, 1)).days

但要注意结果将是错误的,如果12月,你需要改进它如下:

完整代码:

import datetime

def days_in_month(year, month):
    """
    Inputs:
      year  - an integer between datetime.MINYEAR and datetime.MAXYEAR
              representing the year
      month - an integer between 1 and 12 representing the month

    Returns:
      The number of days in the input month.
    """

    #if month is december, we proceed to next year
    def month_december(month):
        if month > 12:
            return month-12  #minus 12 if cross year.
        else:
            return month

    #if month is december, we proceed to next year
    def year_december(year, month):
        if month > 12:
            return year + 1
        else:
            return year

    #verify if month/year is valid
    if (month < 1) or (month > 12):
        print ("please enter a valid month")
    elif (year < 1) or (year > 9999):
        print ("please enter a valid year between 1 - 9999")
    else:
        #subtract current month from next month then get days
        date1 = (datetime.date(year_december(year, month+1), month_december(month+1), 1) - datetime.date(year, month, 1)).days
        print (date1)

days_in_month(1997, 12)
days_in_month(1998, 1)
days_in_month(1998, 2)

测试用例

days_in_month(1997, 12)
days_in_month(1998, 1)
days_in_month(1998, 2)

<强>输出

31
31
28
[Finished in 0.187s]