栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现对输入日期计算日期为当年第几天

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python实现对输入日期计算日期为当年第几天

设计思路:1)首先定义一个日期接收参数

    2)然后将日期参数中的年,月,日分割提取出来(并转换为整数)

3)判断输入的日期是否正确

4)判断闰年还是平年,如果平年,那么定义的一个标识变量为0,如果是闰年,那么定义的标识变量为1,然后遍历月份求和

5)循环的值加上day,就是要计算的结果

date_str = input("请按’2020-05-05‘格式,输入年月日:")
# year, month, day = int(time_date[:4]), int(time_date[4:6]), int(time_date[6:])  # 将输入的数字拆分
year = int(date_str.split("-")[0])
month = int(date_str.split("-")[1])
# print(month)
day = int(date_str.split("-")[2])
# print(day)
month_set = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 12个月的天数

if 0 < month < 12 and 0 < day < 32:  # 判断月日输入的正确与否
    print('你输入的日期格式正确')
else:
    print('你输入的日期格式不正确,请重新输入')

if (year % 400 == 0) or (year % 4 == 0) and (year % 100 != 0) and (month > 2):  # 判断是否为闰年且输入月份是否大于2
    d_sum = 1
else:
    d_sum = 0

i = 0
for i in range(month - 1):  # 遍历完整月份天数
    if i < (month - 1):
        d_sum += month_set[i]  # 将完整月份天数求和
        i += 1

d_sum += day  # 完整月份天数求和后,在加上day

print("%d年%d月%d日是这一年的第%d天" % (year, month, day, d_sum))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号