Python 判断闰年,判断日期是当前年的第几天

http://www.cnblogs.com/vamei/archive/2012/07/19/2600135.html

Python小题目 针对快速教程 作业答案

写一个程序,判断2008年是否是闰年。

写一个程序,用于计算2008年10月1日是这一年的第几天?(2008年1月1日是这一年的第一天)

 1 #判断闰年
 2 def is_leap_year(year):
 3     return  (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
 4 #判断是这一年的第几天
 5 def getDayInYear(year,month,day):
 6     month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 7     if is_leap_year(year):
 8         month_day[1]=29
 9     return sum(month_day[:month - 1]) + day
10 
11 print(getDayInYear(2008,1,1))
12 print(getDayInYear(2008,10,1))
13 print(getDayInYear(2009,10,1))

也有现成的方法 time strftime() 参考该方法说明 点击链接 http://www.runoob.com/python/att-time-strftime.html

import datetime
def getDayInYear(year, month, day):
    date = datetime.date(year, month, day)
    return date.strftime('%j')
print(getDayInYear(2008,1,1))
print(getDayInYear(2008,10,1))
print(getDayInYear(2009,10,1))
原文地址:https://www.cnblogs.com/IT-Bear/p/7723298.html