""" 作者:范文武 功能:输入某年某月某日,判断是这一年中的第几天? 版本:4.0 日期:2018/11/26 2.0 新增功能:用元组替换列表 3.0 新增功能:将月份划分为不同的集合再操作 4.0 新增功能:将月份及其对应天数通过字典表示 """ """ 需求:输入某年某月某日,判断是一年中的第几天? 思路:每个月份的天数不同,闰年与平年的2月份天数不同 四年一闰,百年不闰,四百年再闰 用字典存入月份与天数,天数设为key值,月份设为value 步骤:1.定义一个函数用来封装判断是否为闰年 2.输入日期,解析时间字符串 3.分别提取解析的时间字符串 4.用字典存入天数相同的月份key值与value 5.遍历月份,计算输入的日期是本年的第几天 """ # ************************************************************ from datetime import datetime def is_leap_year(year): """ 判断闰年 """ if ((year % 4 == 0 and (year % 100 ==0))) or (year % 400 == 0): return True return False def main(): """ 主函数 """ # 输入日期,解析时间字符串 input_date_str = input('请输入年月日(yyyy/mm/dd):') input_date = datetime.strptime(input_date_str,'%Y/%m/%d') # 提取 year = input_date.year month = input_date.month day = input_date.day # 用字典存入相同天数的key值,月份-天数 month_day_dict = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} days = 0 days += day # 遍历月份,计算输入的日期是本年的第几天 for i in range(1, month): days += month_day_dict[i] if is_leap_year(year) and month > 2: days += 1 print('这是{}年的第{}天'.format(year, days)) if __name__ == '__main__': main() # ************************************************************* """ 学习笔记: 字典: 字典的遍历: 1.遍历所有的key for key in d.keys(): print(key) 2.遍历所有的value for value in d.values(): print(value) 3.遍历所有的数据项: for item in d.items(): print(items) strftime()中提供了许多格式化日期字符串的操作: https://docs.python.org/3/library/time.html#time.strftime """
判断日期_v4.0
猜你喜欢
转载自blog.csdn.net/y1363127458/article/details/84535256
今日推荐
周排行