Python习题:给定一个日期字符串(eg:2013-12-31),判断输入日期是当年中的第几天?

 1 def isleapyear(year):                              #判断是否为闰年
 2     if (year % 4 == 0 and year % 100 != 0) or (year %400 == 0):
 3         leap_flag = 1
 4     else:
 5         leap_flag = 0
 6     return leap_flag
 7 
 8 while True:
 9     month_list = [31,28,31,30,31,30,31,31,30,31,30,31] 
10     date = input("请输入日期:")
11     try:                                               #当用户不按格式输入时,进行提示
12         date_list = date.split('-')
13         year = int(date_list[0])
14         month = int(date_list[1])
15         day = int(date_list[2])
16     except IndexError:
17         print("请按照'xxxx-xx-xx'格式输入日期")
18     except ValueError:
19         print("请按照'xxxx-xx-xx'格式输入日期")
20     else:
21         sum = 0
22         flag = isleapyear(year)
23         if month != 1:                                #月份不为1月时,循环并相加之前月份的天数和,再加上本月的天数
24             for n in range(0,month-1):
25                 sum += month_list[n]
26             sum += day
27             if flag and month > 2:                   #如果为闰年且月份大于2月,总数加1
28                 sum += 1 
29         else:                                        #月份为1月时,直接提取天数
30             sum = day
31 
32         print("输入的日期是当年中的第 %d 天" % sum)
33     

猜你喜欢

转载自www.cnblogs.com/felixqiang/p/10312026.html