Python 计算日期是该年的第几天
以下是 Python 代码实现:
def day_of_year(year, month, day):
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
days_in_month[1] = 29
total_days = sum(days_in_month[:month-1]) + day
return total_days
函数接收三个参数:年、月、日。首先定义了一个列表 'days_in_month',里面存储了每个月份对应的天数。如果是闰年,修改二月的天数为 29。然后计算该日期之前的天数总和,即为该日是该年的第几天。最后返回总天数。
原文地址: https://www.cveoy.top/t/topic/oad4 著作权归作者所有。请勿转载和采集!