【基础入门题】2021.11.08
给定日期是该年的第几天?
比如:
输入“2020/03/02"或者“2020-03-02”,则输出:62;
输入“2021/03/02"或者“2021-03-02”,则输出:61;
输入“2021/11/08"或者“2021-11-08”,则输出:312;
输入“2021/11-08"或者“2021/11-08”,格式错输出为空。
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
方法一:累加每个月的天数列表
def DaysofYear(strDate): Days = [31,28,31,30,31,30,31,31,30,31,30,31] if strDate.count('/')==2: try: listDate = list(map(int,strDate.split('/'))) except: listDate = None elif strDate.count('-')==2: try: listDate = list(map(int,strDate.split('-'))) except: listDate = None else: listDate = None if listDate: year,month,day = listDate if year%4==0 and year%100!=0 or year%400==0: Days[1] = 29 return sum(Days[:month-1])+day else: return None >>> DaysofYear('2020-03-02') 62 >>> DaysofYear('2021-03-02') 61 >>> DaysofYear('2021/11/08') 312 >>> DaysofYear('2021/11-08') >>>
方法二:使用datetime库
def DaysofYear(strDate): from datetime import date try: d = [int(i) for i in strDate.split('/')] except: try: d = [int(i) for i in strDate.split('-')] except: return None if len(d)!=3: return None d1 = date(d[0],d[1],d[2]) d2 = date(d[0],1,1) diff = d1 - d2 return diff.days + 1 >>> DaysofYear('2021-03-02') 61 >>> DaysofYear('2020-03-02') 62 >>> DaysofYear('2021/11/08') 312 >>> DaysofYear('2021/11-08') >>>