Given a certain year, month and day, use python to judge this is the day of the year

Given a certain year, month and day, use python to judge this is the day of the year

How to judge the month and day first? Take March 5th as an example, which means adding up the days in two months and then adding the days in this month. At the same time, there is another factor to consider-if it is a leap year and the input month is greater than 3, you need to consider adding one more day.
Let's look at the first part first. First define the year, month and day to be used, so that it will be input from the keyboard for convenience. At the same time, we already know that if the first month has 31 days, the second month is a leap year, then 31+28 days is 59 days, the third month is 90 days, and so on.

year=input('year:\n')
year=int(year)
month=input('month:\n')
month=int(month)
day=input('day:\n')
day=int(day)
months=(0,31,59,90,120,151,181,212,243,273,304,334)

Let’s look at the second part again. First, let’s make a judgment. Normally, a year is only 12 months. If it is not, it is wrong. The second is a leap year judgment, which is divisible by 400 or divisible by 4 but not divisible by 100. Yes, it is a leap year. As long as the number of months is greater than 2, the number of days will be one more day.

if 0<month<=12:
    sum =months[month-1]
else:
    print('data error')
sum+=day
leap=0
if(year %400 ==0)or ((year%4==0)and(year&100!=0)):
        leap=1
if(leap==1)and (month>2):
            sum+=1
print('it is the %dth day.'%sum)

Below is an input example

year:
2015
month:
6
day:
7
it is the 158th day.

Guess you like

Origin blog.csdn.net/weixin_47567401/article/details/112793771