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

输入某年某月某日,判断这一天是这一年的第几天?(Python)

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

输入某年某月某日,判断这一天是这一年的第几天?(Python)

输入某年某月某日,判断这一天是这一年的第几天?

当时老师让我们做这道题是想锻炼我们的“选择循环方法”,所以用选择循环方法:

第一种方法解析:

1,3,5,7,8,10,12三十一天永不差,其余是30天,2月是28天(闰年是29天)
先假设每一个月都是30天,然后再计算有几个31天和28(或29天)的月份
1-2月是一个计算段,3-7是一个计算段,8-12是一个计算段

代码
date = input('输入某年某月某日,格式为:****-**-**,小于10请写0*:')
# 使用切片截取年,月,日
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
# 判断是否是闰年,并为每一月赋值
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    feb = 29
else:
    feb = 28
# 1-2月是一个计算段,3-7是一个计算段,8-12是一个计算段
result = 0
if feb == 29:
    if 1 <= month <= 2:
        result = (month - 1) * 30 + day + int(month / 2)
    elif 2 < month <= 7:
        result = (month - 1) * 30 + day + int(month / 2) - 1
    elif 12 >= month > 7:
        result = 213 + (month - 8) * 30 + day + int((month - 7) / 2)
elif feb == 28:
    if 1 <= month <= 2:
        result = (month - 1) * 30 + day + int(month / 2)
    if 2 < month <= 7:
        result = (month - 1) * 30 + day + int(month / 2) - 2
    elif 12 >= month > 7:
        result = 212 + (month - 8) * 30 + day + int((month - 7) / 2)

print('{}-{}-{}是一年中的第{}天'.format(year, month, day, result))

上面是我自己写的代码,然后我查阅了一下其他人写的,顿时发现我写的好low

第二种方法解析

一年12个月份放入列表中,其中二月特殊表示(闰年29天,其他28天),

代码
date = input('输入某年某月某日,格式为:****-**-**,小于10请写0*:')
# 使用切片截取年,月,日
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
# 判断是否是闰年,并为每一月赋值
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    feb = 29
else:
    feb = 28
date1 = [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
res = 0
i = 0
for i in date1[0:month - 1]:
    res = res + i
res += day
print('{}-{}-{}是一年中的第{}天'.format(year, month, day, res))
第三种方法,如果配合Python中的 calendar 标准库,可以把判断闰年的一长串代码直接用isleap()函数代替 代码
import calendar

if calendar.isleap(year):
    feb = 29
else:
    feb = 28
date2 = [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
res = 0
i = 0
for i in date2[0:month-1]:
    res = res + i
res += day
print('{}-{}-{}是一年中的第{}天'.format(year, month, day, res))
结果

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

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

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