You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MicroPython或RTC DS1307中判断指定年月的月末日期?

纯MicroPython实现给定年月的月末日期计算

你可以通过以下纯MicroPython代码实现该需求,无需依赖任何RTC模块或外部库,核心基于月份天数规则和闰年判断逻辑:

实现逻辑

  1. 非闰年的月份天数固定:[31,28,31,30,31,30,31,31,30,31,30,31](对应1-12月)
  2. 二月天数需根据闰年调整:闰年为29天,非闰年为28天
  3. 闰年判断规则:
    • 能被4整除但不能被100整除,或者能被400整除的年份为闰年

代码实现

def get_last_day(year, month):
    # 校验月份合法性
    if not (1 <= month <= 12):
        raise ValueError("月份必须在1-12之间")
    
    # 非闰年各月份天数
    month_days = [31,28,31,30,31,30,31,31,30,31,30,31]
    
    # 处理二月的闰年情况
    if month == 2:
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            return 29
    
    # 返回对应月份的天数
    return month_days[month - 1]

测试示例

# 测试2023年各月份
print(get_last_day(2023, 1))  # 输出31
print(get_last_day(2023, 2))  # 输出28
print(get_last_day(2023, 3))  # 输出31

# 测试闰年二月
print(get_last_day(2020, 2))  # 输出29
print(get_last_day(2000, 2))  # 输出29(能被400整除的闰年)
print(get_last_day(1900, 2))  # 输出28(能被100整除但不能被400整除,非闰年)

该代码可直接在Raspberry Pi Pico的MicroPython环境中运行,完全不依赖硬件模块,仅通过日期规则计算月末日期。

内容的提问来源于stack exchange,提问作者Łukasz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:05:22