一、判断某年的年份是否为闰年?
# function:Judging whether a year is a leap year
year = input("Please enter the year you want to judge: ")
if year.isdigit():
year = int(year)
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year, "is leap year!")
else:
print(year, "is not leap year!")
else:
print("Please enter the correct year!")
exit()
二、判断指定日期为该年中的第多少天?
法一:无调用第三方模块
# Calculate how many days of the year the specified time is
date = "2019-12-31"
temp = 0
year = int(date.split("-")[0])
def leapyear(y):
return (y % 4 == 0 and y % 100 != 0 or y % 400 == 0)
month_day = [0,31,28,31,30,31,30,31,31,30,31,30]
if leapyear(year):
month_day[2] += 1
month = int(date.split("-")[1])
day = int(date.split("-")[2])
for i in range(month):
temp += month_day[i]
few_day = temp + day
print("%s is the %s day of %s"%(date,few_day,year))
法二:调用datetime计算
# Calculate how many days of the year the specified time is
import datetime
year = int(input("please enter years:"))
month = int(input("please enter months:"))
day = int(input("please enter days:"))
def fewday(y,m,d):
TargetDay = datetime.date(y,m,d)
InitialDay = datetime.date(y,1,1)
return (TargetDay - InitialDay).days + 1
result = fewday(year,month,day)
print("%s-%s-%s is the %s day of %s"%(year,month,day,result,year))