- 本示例目标:进行一年中的天数的计算“一年中的第几天”视频教程
- 本示例涉及的知识点:
①元组——计算年份
②改写成函数判断模块;用数组改写(元组不能重新赋值)list[1]=29 ;
③元组与数组的区别
④多个数据的集合
⑤datatime库,通过日期解析周数
⑥字典——键值对数据组合
⑦字典的遍历等
"""
版本:1.0
日期:01.03.2020
功能:用数据字典来存储数据
"""
from datetime import datetime
def is_leap_year(year):
"""
判断year是否为闰年
是,返回true
否,返回false
"""
is_leap = False
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
is_leap = True
return is_leap
def main():
"""
主函数
"""
input_date_str = input('请输入日期(yyyy/mm/dd):')
input_date = datetime.strptime(input_date_str, '%Y/%m/%d')
print(input_date)
year = input_date.year
month = input_date.month
day = input_date.day
# 不同天数月份集合
# _30_days_set = {4, 6, 9, 11}
# _31_days_set = {1, 3, 5, 7, 8, 10, 12}
month_day_dict = {1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31}
# 这是一个思考题,如果用天作 键 的话,月份做值,那么这个应该怎么写呢
# day_month_dict = {31: {1, 3, 5, 7, 8, 10, 12},
# 30: {4, 6, 9, 11},
# 28: {2}}
days = 0
days += day
for i in range(1, month):
days += month_day_dict[i]
# 计算之前月份天数总和以及当前月份的天数
days_in_month_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
days_in_month_list[1] = 29
days = sum(days_in_month_list[:month - 1]) + day
# # 判断闰年
# if month > 2 and is_leap_year(year):
# days += 1
print("这是第{}年的第{}天".format(year, days))
if __name__ == "__main__":
main()
来源:CSDN
作者:LuxBaaJane
链接:https://blog.csdn.net/qq_41553157/article/details/103821552