给你一个按 YYYY-MM-DD
格式表示日期的字符串 date,请你计算并返回该日期是当年的第几天。
通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。
方法一:
找规律。2,7,8都是节点。可以先把2月当做30天算,方便找规律。
class Solution:
def dayOfYear(self, date: str) -> int:
splitList = date.split('-')
listStr = []
for ch in splitList:
listStr.append(int(ch))
if (listStr[0] % 4 == 0 and listStr[0] % 100 != 0) or (listStr[0] % 400 == 0):
feb = 1
else:
feb = 2
if listStr[1] <= 2:
feb = 0
if listStr[1] < 8:
return int(31*( (listStr[1] )//2 ) + 30*((listStr[1] - 1)//2) - feb + listStr[2])
if listStr[1] >= 8:
return int(31*( (listStr[1] -1)//2 + 1) + 30*((listStr[1] - 2)//2) - feb + listStr[2])
方法二:利用库函数
python比其他语言的优点就是具有比较多的高级实现和库函数。
from datetime import date
class Solution:
def dayOfYear(self, dt: str) -> int:
y, m, d = [int(x) for x in dt.split('-')]
start = date(y, 1, 1)
cur = date(y, m, d);
diff = cur - start
return diff.days + 1
方法三:days 表示前面月份含有多少天。
class Solution(object):
def dayOfYear(self, date):
date = date.split('-')
year = int(date[0])
month = int(date[1])
day = int(date[2])
days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 4 == 0 and year % 100 != 0:
days[2] = 29
if year % 400 == 0:
days[2] = 29
for i in range(1, month ):
days[i] += days[i - 1]
return days[month - 1] + day
"""
:type date: str
:rtype: int
"""