Python程序设计
输入一年中的年月日,判断这一天是这一年的第几天
import re
ymd=input('请输入yyyy-mm-dd格式日期:')
if re.match(r"^\d{4}(-\d{2}){2}$",ymd):
year,month,day=map(int,ymd.split('-'))
isRN=year%400==0 or (year%4==0 and year%100!=0)
mth_days=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in range(month-1):
day+=mth_days[i]
if month>2 and isRN:
day+=1
print('第%d天'%day)
else:
print('input error')
定义一个月份天数数组。然后根据月数统计之前所有月的总天数加上当前的日期,最后再判断年是否为闰年,如果是闰年且过了2月,则加1天
#输入某年某月某日,判断这一天是这一年的第几天?
year=int(input('请输入年份:'))
month=int(input('请输入月份:'))
day=int(input('请输入日期:'))
months=[0,31,28,31,30,31,30,31,31,30,31,30,31] #定义一年里1-12月每月的天数(将month值作为数组下标)
if year%400==0 or (year%4==0 and year%100 != 0): #如果是闰年,那么2月份天数需要加1成为29天
months[2]=months[2]+1
if 0<month<=12: #要求月份必须输入1到12
days=0 #总天数
for item in range(month): #根据输入月份,计算该月之前所有月份的天数之和
sum=months[item]
days=days+sum
day_s=days+day #最后再加指定月份的天数,就是指定日期在指定年份的总天数
print(f'今天是今年的第{day_s}天')
else:
print('输入日期超出范围')
year=int(input('请输入年份,如2019>>>'))
month=int(input('请输入月份,如8>>>'))
day=int(input('请输入日期,如25>>>'))
#下面这块代码是按照闰年计算
if (year%4==0 and year%100!=0) or (year%400==0):
calendar={1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
if month==1:
print('这一天是这一年的第',day,'天')
else:
past_months=range(1,month)
#上面这行代码是计算已经过了多少个月,假设用户输入的是5月,那么这里就统计1到4月
past_days=day
#当月的日期一定要先加进去,比如用户输入5月18日,那么18肯定是要算进去的
for m in past_months:
past_days=past_days+calendar[m]
print('这一天是这一年的第',past_days,'天')
#下面这块代码是按照平年计算
else:
calendar={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
if month==1:
print('这一天是这一年的第',day,'天')
else:
past_months=range(1,month)
past_days=day
for m in past_months:
past_days=past_days+calendar[m]
print('这一天是这一年的第',past_days,'天')