【基础入门题012】给定日期是该年的第几天

【基础入门题】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')
>>> 

欢迎加入csdn社区!icon-default.png?t=LA92https://bbs.csdn.net/forums/PythonTogether

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值