《学习记录》“Python”计算距离生日还有多久

  • Post author:
  • Post category:python


题目要求:

输入出生年和月,然后计算出接下来的生日距离今天还有多久。

代码如下:


if __name__ == '__main__':
   #计算距离生日还有多久
    import datetime
    import time
    year = int(input("请输入出生年:")) #未起作用
    month = int(input("请输入出生月:"))
    day = int(input("请输入出生日:"))
    now = datetime.datetime.now()   #获取当前时间
    print("当前的时间是:%s" %now)
    nowyear = now.year              #将当前年月日赋值
    nowmonth = now.month
    nowday = now.day
    nextyear = nowyear+1
    if nowmonth > month:            #判断是否已经过生日了
            month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            if nextyear % 400 == 0 or nextyear % 100 != 0 and nextyear % 4 == 0:        #判断是否闰年
                month_day[1] = 29
            otherday = sum(month_day[:month - 1]) + day                 #明年生日在明年的第几天

            month_day[1] = 28
            if nowyear % 400 == 0 or nowyear % 100 != 0 and nowyear % 4 == 0:           #判断是否闰年
                month_day[1] = 29
            anotherday = sum(month_day[:nowmonth - 1]) + nowday         #今天是今年第几天
            if nowyear % 400 == 0 or nowyear % 100 != 0 and nowyear % 4 == 0:
                expectday = 366 - anotherday
            else:
                expectday = 365 - anotherday
            print("距离生日还有{0}".format(expectday+otherday))
    else:
            month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            if nowyear % 400 == 0 or nowyear % 100 != 0 and nowyear % 4 == 0:           #判断是否闰年
                month_day[1] = 29
            anotherday = sum(month_day[:nowmonth - 1]) + nowday             #计算今天是今年第几天
            month_day[1] = 28
            if nowyear % 400 == 0 or nowyear % 100 != 0 and nowyear % 4 == 0:
                month_day[1] = 29
            otherday = sum(month_day[:month - 1]) + day                     #计算生日是今年第几天
            print("距离生日还有{0}".format(otherday-anotherday))

思路:

1、首先先向程序输入生日的日期

2、判断是不是今年过生日

3、判断闰年平年

4、计算出今天是今年的第几天

5、计算出生日是第几天

6、如果是今年过生日,则用生日在今年第几天减去今天是今年的第几天

7、如果是明年过生日,则先计算出今年还有多少天,然后用剩余天数加上生日在明年第几天

———————————————————————————————————————————

相信还有更加简单的方法,作者水平有限。仅为记录学习……



版权声明:本文为weixin_57725017原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。