1. 程式人生 > >Python:輸入年月日判斷是此年的第多少天

Python:輸入年月日判斷是此年的第多少天

方法一:

#!\usr\bin\python
# coding=utf-8


year = int(raw_input("year:"))
month = int(raw_input("month:"))
day = int(raw_input("day:"))


the_month1 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]#平年
the_month2 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]#閏年


if ((year % 4 == 0)and(year % 100 != 0))or(year % 400 == 0):
    sumday = the_month2[month-1]+day
else:
    sumday = the_month1[month-1]+day


print "這是第 %d 天"%sumday

結果:

E:\Python27\python.exe E:/PycharmProjects/file/guesstheday.py
year:2015
month:6
day:7
這是第 158 天


Process finished with exit code 0

方法二:

#!\usr\bin\python
# coding=utf-8


year = int(raw_input("year:"))
month = int(raw_input("month:"))
day = int(raw_input("day:"))
the_month1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]#平年
sumday = day
for m in range(0, month-1):
    sumday = sumday+the_month1[m]
if ((year % 4 == 0)and(year % 100 != 0))or(year % 400 == 0):
    if(month>2):#此處要考慮若輸入的月份沒有超過2,就不用加1
        sumday=sumday+1
        print "這是第 %d 天" % sumday
    else:
        print "這是第 %d 天" % sumday
else:
    print "這是第 %d 天"%sumday



方法三:

#!\usr\bin\python
# coding=utf-8


import time


D = raw_input("請輸入年份:格式為YYYY-MM-DD")
d = time.strptime(D, '%Y-%m-%d').tm_yday
print "the {} day of this year!".format(d)