python求输入某年某月某日,判断这一天是这一年的第几天
#方法一:
y=int(input(‘请输入四位数年份:’))
m=int(input(‘请输入月份:’))
d=int(input(‘请输入是哪一天:’))
Month_days=[31,28,31,30,31,30,31,31,30,31,30,31]
if y%4== 0:
Month_days[1]=29
if m not in range(1,13):
print(‘请输入正确月份!’)
elif d not in range(1,Month_days[m-1]+1):
print(‘请输入正确日期!’)
else:
s= sum(Month_days[0:m-1])+d
print(‘这一天是这一年的第%d天.’%(s))
运行结果:
方法二:
import datetime
y=int(input(‘请输入四位数年份:’))
m=int(input(‘请输入月份:’))
d=int(input(‘请输入是哪一天:’))
Month_days=[31,28,31,30,31,30,31,31,30,31,30,31] #这里用来判断日期输入是否正确
if y%4== 0:
Month_days[1]=29
if m not in range(1,13):
print(‘请输入正确月份!’)
elif d not in range(1,Month_days[m-1]+1):
print(‘请输入正确日期!’)
else:
s= sum(Month_days[0:m-1])+d
targetDay = datetime.date(y,m,d)
print(targetDay-datetime.date(targetDay.year-1,12,31))
运行结果:
targetDay = datetime.date(y,m,d)
#print(targetDay-datetime.date(targetDay.year-1,12,31))
dayCount = targetDay-datetime.date(targetDay.year-1,12,31)
print(dayCount.days)
结果: