题目
给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
示例1:
输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。
示例2:
输入:date = "2019-02-10"
输出:41
提示:
(1)date.length == 10
(2)date[4] == date[7] == '-',其他的 date[i] 都是数字
(3)date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
分析思路
本题需要注意的点在于:
1、判断年份是否为闰年(能被400整除,或者能被4整除但不能被100整除);
满足以下两个条件的整数才可以称为闰年:
(1)普通闰年:能被4整除但不能被100整除(如2004年就是普通闰年);
(2)世纪闰年:能被400整除(如2000年是世纪闰年,1900年不是世纪闰年);
2、输入的日期为字符串类型,如何提取年、月、日(考虑利用切片);
3、如何进行计算(将提取的字符串转换为数值型int)。
整体思路:
法一:将每个月份的天数以数组存放(2月份天数按28天记),判断当前年份是否为闰年,若为闰年,则将自定义数组中2月份的天数改为29,接着利用切片计算已度过的月份天数+当月天数。
class Solution(object):
def dayOfYear(self, date):
#每月天数存为数组,注意7、8月天数均为31天
days = [0,31,28,31,30,31,30,31,31,30,31,30,31,30]
#判断当前年份是否为闰月,若是,将2月份的天数换成29天
now_year = int(date[:4])
if now_year % 4 == 0 and now_year % 100 != 0 or now_year % 400 == 0 :
days[2]=29
#计算天数
res = sum(days[ : int(date[5:7])])+int(date[8:])
return res
LeetCode参考答案:
class Solution(object):
def dayOfYear(self, date):
"""
:type date: str
:rtype: int
"""
def check(year):
if year % 100 == 0:
return year % 400 == 0
return year % 4 == 0
days = [0, 31,28,31,30,31,30,31,31,30,31,30,31]
if check(int(date[:4])):
days[2] = 29
return sum(days[:int(date[5:7])]) + int(date[8:])
法二 (不推荐):
利用time.strptime() 函数,函数根据指定的格式把一个时间字符串解析为时间元组
语法:
time.strptime(string[, format])
使用方法:
import time
struct_time = time.strptime("30 Nov 00", "%d %b %y")
print "返回的元组: %s " % struct_time
运行结果:
返回的元组: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
本题用该法解题代码如下:
import time
class Solution(object):
def dayOfYear(self, date):
"""
:type date: str
:rtype: int
"""
return time.strptime(date, "%Y-%m-%d")[-2]