您现在的位置是:首页 > 编程语言学习 > 前端编程语言 > 文章正文 前端编程语言

python实现对输入日期计算日期判断为当年第几天

2022-05-31 10:18:44 前端编程语言

简介本文实例讲述了Python编程实现输入某年某月某日计算出这一天是该年第几天的方法。分享给大家供大家参考。设计思路:1)首先定义一个日期接...

本文实例讲述了Python编程实现输入某年某月某日计算出这一天是该年第几天的方法。分享给大家供大家参考。

设计思路:

1)首先定义一个日期接收参数

2)然后将日期参数中的年,月,日分割提取出来(并转换为整数)

3)判断输入的日期是否正确

4)判断闰年还是平年,如果平年,那么定义的一个标识变量为0,如果是闰年,那么定义的标识变量为1,然后遍历月份求和

5)循环的值加上day,就是要计算的结果

  1. date_str = input("请按’2020-05-05‘格式,输入年月日:"
  2. # year, month, day = int(time_date[:4]), int(time_date[4:6]), int(time_date[6:])  # 将输入的数字拆分 
  3. year = int(date_str.split("-")[0]) 
  4. month = int(date_str.split("-")[1]) 
  5. # print(month) 
  6. day = int(date_str.split("-")[2]) 
  7. # print(day) 
  8. month_set = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 12个月的天数 
  9.   
  10. if 0 < month < 12 and 0 < day < 32:  # 判断月日输入的正确与否 
  11.     print('你输入的日期格式正确'
  12. else
  13.     print('你输入的日期格式不正确,请重新输入'
  14.   
  15. if (year % 400 == 0) or (year % 4 == 0) and (year % 100 != 0) and (month > 2):  # 判断是否为闰年且输入月份是否大于2 
  16.     d_sum = 1 
  17. else
  18.     d_sum = 0 
  19.   
  20. i = 0 
  21. for i in range(month - 1):  # 遍历完整月份天数 
  22.     if i < (month - 1): 
  23.         d_sum += month_set[i]  # 将完整月份天数求和 
  24.         i += 1 
  25.   
  26. d_sum += day  # 完整月份天数求和后,在加上day 
  27.   
  28. print("%d年%d月%d日是这一年的第%d天" % (year, month, day, d_sum)) 

 

站点信息