zoukankan      html  css  js  c++  java
  • python基础-判断一年中的第几天

    问题:

    用函数实现输入某年某月某日,判断这一天是这一年的第几天?闰年情况也考虑进去
    如:20160818,是今年第x天。

    代码实现:

    import copy
    from functools import reduce
    
    
    def rankDay(date_str):
        '''
        计算日期为当年的第x天
        :param date_str: 日期
        :return sum_days: x天
        '''
        # listx = [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]
        list1_p = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 平年
        list2_r = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 闰年
        # print(reduce(lambda x, y: x + y, list1))
        # print(reduce(lambda x, y: x + y, list2))
        if len(date_str) == 8 and date_str.isnumeric():
            # 输入验证正确后1
            # 获取年月日
            year_int = int(date_str[0:4])
            month_int = int(date_str[4:6])
            day_int = int(date_str[6:8])
            # print(year_int)
            # print(month_int)
            # print(day_int)
    
            if (month_int >= 1 and month_int <= 12) and (day_int >= 1 and day_int <= 31):
                # 进一步验证输入数的正确性2
                #  计算天数
    
                # 判断润平年。平年有365天,闰年有366天。
                days_list = []  # 计算使用的日子列表
                month_days = 0  # 计算使用的前面整月的天数和
                day_days = 0  # 计算使用的本月的天数和
                if year_int % 400 == 0 or (year_int % 4 == 0 and year_int % 100 != 0):
                    # 闰年。366天
                    days_list = copy.deepcopy(list2_r)  # 深拷贝
                else:
                    # 平年。356天
                    days_list = copy.deepcopy(list1_p)  # 深拷贝
    
                # 计算前面多个整月的天数
                if month_int - 1 > 0:
                    # 前面有多个整月
                    list_cal = days_list[0:(month_int - 1)]
                    # print(list_cal)
                    month_days = reduce(lambda x, y: x + y, list_cal)
    
                else:
                    month_days = 0
    
                # 计算本月的天数
                day_days = day_int
    
                # 计算总天数
                sum_days = month_days + day_days
                print("%s是%s年的第%s天" % (date_str, year_int, sum_days))
                return sum_days
    
            else:
                print("请输入正确的格式,如:20160101。月份不大于12,日子不大于31")
    
        else:
            print("请输入正确的格式,如:20160101")
    
    
    if __name__ == '__main__':
        while True:
            date_str = input("请输入日期(如:20160101):").strip()
            sum_days = rankDay(date_str)
            print(sum_days)
    

      

  • 相关阅读:
    EMIF接口的寻址问题
    C6000系类的内联函数
    C6000代码层面优化(一)
    RHCE学习笔记
    找出并关闭Ruby On Rails进程.
    Rails4添加bootstrap支持
    如何删除gnome3面板上的图标?
    出现 ruby cannot load such file -- zlib 问题的解决方法
    Debian安装软件时提示插入光盘
    Debian7桌面屏蔽图标和右键菜单的解决方法。
  • 原文地址:https://www.cnblogs.com/andy9468/p/13025836.html
Copyright © 2011-2022 走看看