5.5 日期分析处理python |
您所在的位置:网站首页 › Sept缩写 › 5.5 日期分析处理python |
第1关 判断闰年, 第2关 输出当前月份共有多少, 第3关 日期转换格, 第4关 判断日期合法, 第5关 月份的英文名 第1关 判断闰年 代码如下: def leap(current_date): """接收一个用8个字符表示日期的字符串为参数,判断这个日期中的年份是否为闰年 返回值为布尔型。 闰年的判定方法是:能被400整除或能被4整除且同时不能被100整除的是闰年。 """ # 补充你的代码 if (int(current_date[:4]) % 4 ==0 or int(current_date[:4]) % 400 ==0) and int(current_date[:4]) % 100 !=0: return True else: return False if __name__ == '__main__': date = input() # 输入一个表示年份的8位数字字符串 if leap(date[:4]): # 如果输入的年份是闰年 print(f'{date[:4]}年是闰年') else: print(f'{date[:4]}年不是闰年')第2关 输出当前月份共有多少 代码如下: def days_of_month(current_date): """接收一个用8个字符表示日期的字符串为参数,计算这个日期中的月份有多少天?返回值为整型, 表示当前月份天数。 @参数 current_date:表示日期,字符串类型 """ # 补充你的代码 dm = [31,28,31,30,31,30,31,31,30,31,30,31] if leap(current_date): dm[1] = 29 days = dm[(int(CurrentDate[4:6])-1)] return days def leap(current_date): """接收一个用8个字符表示日期的字符串为参数,判断这个日期中的年份是否为闰年 返回值为布尔型。 闰年的判定方法是:能被400整除或能被4整除且同时不能被100整除的是闰年。 """ # 补充你的代码 if (int(current_date[:4]) % 4 ==0 or int(current_date[:4]) % 400 ==0) and int(current_date[:4]) % 100 !=0: return True else: return False if __name__ == '__main__': CurrentDate = input() days = days_of_month(CurrentDate) print(f'{CurrentDate[:4]}年{int(CurrentDate[4:6])}月有{days}天')第3关 日期转换格 代码如下: def separate_date(current_date, symbol): """接收一个用8个字符表示日期的字符串和一个符号为参数,返回用该符号分隔的日期,字符串类型。 @参数 current_date:表示日期,字符串类型 @参数 symbol:分隔符号,字符串类型 例如传入'20201031'和"/",返回字符串'2020/09/09' """ # 补充你的代码 return f'{current_date[0:4]}{symbol}{current_date[4:6]}{symbol}{current_date[6:]}' if __name__ == '__main__': CurrentDate = input() # 输入8位数字表示的日期 sign = input() # 输入分隔符 print(separate_date(CurrentDate, sign)) # 输出用分隔符分隔的日期第4关 判断日期合法 代码如下: def legal_judge(current_date): """接收一个用8个字符表示日期的字符串为参数,判定日期的合法性,返回值为布尔型。 1,3,5,7,8,10,12月各31天,4,6,9,11各30天,闰年2月29天,平年2月28天。 @参数 current_date:表示日期,字符串类型 """ # 补充你的代码 dm = [31,28,31,30,31,30,31,31,30,31,30,31] if leap(current_date): dm[1] = 29 if int(CurrentDate[6:]) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |