查找一个月的天数,不要求区分闰月平年,只按平年实现。天数

建立一个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}天")
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7728435
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:用户输入月份,判断这个月份是哪个季节
  • 除此之外, 这篇博客: 数据挖掘 沪深股市预测中的 按照天,月,季度,年来显示比特币的走势 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 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()
    
  • 以下回答由chatgpt基于相关博客总结生成:

    代码实现:

    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))
    

    解释一下具体步骤:

    1. 首先定义一个函数get_days_of_month(),返回一个字典,包含每个月的天数;
    2. 根据字典生成每月天数的字典month_days_dict
    3. 输入年份和月份;
    4. 调用get_days()函数,计算1月到输入月份总共的天数,并返回结果;
    5. 输出月份对应的天数。

    输出结果示例:

    {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天