python判断一年中的第几天_python基础-判断一年中的第几天

问题:

用函数实现输入某年某月某日,判断这一天是这一年的第几天?闰年情况也考虑进去

如:20160818,是今年第x天。

代码实现:

import copy

from functools import reduce

def rankDay(date_str):

'''

计算日期为当年的第x天

:param date_str: 日期

:return sum_days: x天

'''

# listx = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

list1_p = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 平年

list2_r = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 闰年

# print(reduce(lambda x, y: x + y, list1))

# print(reduce(lambda x, y: x + y, list2))

if len(date_str) == 8 and date_str.isnumeric():

# 输入验证正确后1

# 获取年月日

year_int = int(date_str[0:4])

month_int = int(date_str[4:6])

day_int = int(date_str[6:8])

# print(year_int)

# print(month_int)

# print(day_int)

if (month_int >= 1 and month_int <= 12) and (day_int >= 1 and day_int <= 31):

# 进一步验证输入数的正确性2

# 计算天数

# 判断润平年。平年有365天,闰年有366天。

days_list = [] # 计算使用的日子列表

month_days = 0 # 计算使用的前面整月的天数和

day_days = 0 # 计算使用的本月的天数和

if year_int % 400 == 0 or (year_int % 4 == 0 and year_int % 100 != 0):

# 闰年。366天

days_list = copy.deepcopy(list2_r) # 深拷贝

else:

# 平年。356天

days_list = copy.deepcopy(list1_p) # 深拷贝

# 计算前面多个整月的天数

if month_int - 1 > 0:

# 前面有多个整月

list_cal = days_list[0:(month_int - 1)]

# print(list_cal)

month_days = reduce(lambda x, y: x + y, list_cal)

else:

month_days = 0

# 计算本月的天数

day_days = day_int

# 计算总天数

sum_days = month_days + day_days

print("%s是%s年的第%s天" % (date_str, year_int, sum_days))

return sum_days

else:

print("请输入正确的格式,如:20160101。月份不大于12,日子不大于31")

else:

print("请输入正确的格式,如:20160101")

if __name__ == '__main__':

while True:

date_str = input("请输入日期(如:20160101):").strip()

sum_days = rankDay(date_str)

print(sum_days)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值