gottfried

导航

Python小练习之判断一个日期是一年的第几天

python练手遇到的一个问题写了个统一公式,不用麻烦的分各种类,如果有人测试出错误请评论通知。

#分单双月

def dayNum(month,day,isLeap):
    if month % 2 != 0:
        if month == 1:
            days = day
        else:
            days = (month - 1) * 30.5 - 2 + (month // 9) + day + isLeap
    else:
        if month == 2:
            days = 31 + day
        else:
            days = (month - 1) * 30.5 - 1.5 + day + isLeap
    return days

 



# 归类统一不分单双月

def dayNumPro(month,day,isLeap):
    #月份大于九月时会出现差异
    num = ((month // 9) and (month % 2 != 0))
    if month == 1:
        days = day
    elif month == 2:
        days = 31 + day
    else:
        days = (month - 1) * 30.5 - 1.5 - (month % 2)*0.5 + day + isLeap + num
    return days

def dayOfYear():
    year = int(input("请输入年份:"))
    month = int(input("请输入月份:"))
    day = int(input("请输入日:"))
    #判断是否是闰年(取真假1,0来参与运算不用分类)
    isLeap = (year % 4 == 0) and (year % 400 != 0)
    days = dayNumPro(month,day,isLeap)
    print(days)
dayOfYear()

 



posted on 2018-06-02 14:12  gottfried  阅读(981)  评论(0编辑  收藏  举报