建立一个1-12月对应每月天数的字典,任意查找一个月的天数,不要求区分闰月平年,只按平年实现。
fig = plt.figure(figsize=[15, 7])
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.suptitle('上证指数', fontsize=20)
plt.subplot(221)
plt.plot(df.Price, '-', label='按天')
plt.legend()
plt.subplot(222)
plt.plot(df_month.Price, '-', label='按月')
plt.legend()
plt.subplot(223)
plt.plot(df_Q.Price, '-', label='按季度')
plt.legend()
plt.subplot(224)
plt.plot(df_year.Price, '-', label='按年')
plt.legend()
plt.show()
import calendar
def days_in_month(year, month):
# 强制将年份调整为平年
year = calendar.isleap(year) and year or year + 1
# 返回该月份的天数
return calendar.monthrange(year, month)[1]
# 获取用户输入的年份和月份
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 调用函数获取该月份的天数并输出结果
days = days_in_month(year, month)
print(f"{year}年{month}月共有{days}天")
fig = plt.figure(figsize=[15, 7])
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.suptitle('上证指数', fontsize=20)
plt.subplot(221)
plt.plot(df.Price, '-', label='按天')
plt.legend()
plt.subplot(222)
plt.plot(df_month.Price, '-', label='按月')
plt.legend()
plt.subplot(223)
plt.plot(df_Q.Price, '-', label='按季度')
plt.legend()
plt.subplot(224)
plt.plot(df_year.Price, '-', label='按年')
plt.legend()
plt.show()
代码实现:
def get_days_of_month():
calendar = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
return calendar
def get_days(year, month):
calendar = get_days_of_month()
days = 0
for i in range(month): # 注意range的范围是0到month-1
days += calendar.get(i+1, 0) # 获取月份对应的天数
return days
if __name__ == '__main__':
days_of_month = get_days_of_month() # 获取每个月的天数
month_days_dict = {i:days_of_month.get(i, 0) for i in range(1, 13)} # 生成字典
print(month_days_dict) # 输出字典
year = input("请输入年份:")
month = input("请输入月份:")
days = get_days(year, month)
print('这一年%d月有%d天' % (int(month), days))
解释一下具体步骤:
get_days_of_month()
,返回一个字典,包含每个月的天数;month_days_dict
;get_days()
函数,计算1月到输入月份总共的天数,并返回结果;输出结果示例:
{1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
请输入年份:2022
请输入月份:7
这一年7月有212天