方案一:不使用標准庫中的模塊和函數。
def is_leap_year(year): """判斷指定的年份是不是閏年,平年返回False,閏年返回True""" return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def which_day(year, month, date): """計算傳入的日期是這一年的第幾天""" # 用嵌套的列表保存平年和閏年每個月的天數 days_of_month = [ [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ] days = days_of_month[is_leap_year(year)][:month - 1] return sum(days) + date
方案二: 使用標准庫中的datetime
模塊。
import datetime def which_day(year, month, date): end = datetime.date(year, month, date) start = datetime.date(year, 1, 1) return (end - start).days + 1
持續更新ing...