You need to enable JavaScript to run this app. Python中如何将月/年格式字符串转日期取月末并与Odoo日期字段比较
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将月/年格式字符串转日期取月末并与Odoo日期字段比较

月/年格式字符串转当月最后一天并与Odoo日期比较方案

核心逻辑

  • 拆分月/年格式字符串为对应的年、月整数值
  • 计算该自然月的最后一天日期(自动适配闰年2月的天数差异)
  • 输出为Python原生 datetime.date 对象,与Odoo日期字段类型完全匹配,可直接做大小比较

可复用实现代码

首先导入依赖库:

import calendar
from datetime import date

封装通用函数:

def get_month_last_day(month_year_str: str) -> date:
    # 拆分"MM/YYYY"格式字符串为月、年
    month, year = map(int, month_year_str.split("/"))
    # calendar.monthrange返回(当月首日星期数, 当月总天数),直接取总天数即为最后一天的日号
    last_day_of_month = calendar.monthrange(year, month)[1]
    return date(year, month, last_day_of_month)

无calendar库的替代实现:通过下月首日减1天得到当月最后一天
需额外导入timedelta依赖:from datetime import timedelta

def get_month_last_day(month_year_str: str) -> date:
    month, year = map(int, month_year_str.split("/"))
    # 处理12月的跨年场景
    if month == 12:
        next_month_first_day = date(year + 1, 1, 1)
    else:
        next_month_first_day = date(year, month + 1, 1)
    return next_month_first_day - timedelta(days=1)

效果验证(匹配需求示例)

直接调用函数测试需求中的三个输入场景:

# 场景1:08/2021 预期输出2021年8月最后一天 31-08-2021
print(get_month_last_day("08/2021")) # 控制台输出: 2021-08-31
# 场景2:02/2020 闰年2月,预期输出29-02-2020
print(get_month_last_day("02/2020")) # 控制台输出: 2020-02-29
# 场景3:02/2021 平年2月,预期输出28-02-2021
print(get_month_last_day("02/2021")) # 控制台输出: 2021-02-28

如果需要格式化为DD-MM-YYYY的字符串用于展示,可调用strftime方法:

last_day = get_month_last_day("08/2021")
print(last_day.strftime("%d-%m-%Y")) # 输出: 31-08-2021

与Odoo日期字段的比较操作

Odoo的 fields.Date 字段在Python运行层返回的就是原生 datetime.date 类型,无需额外转换,可直接使用比较运算符判断:

# 假设another_date为Odoo模型取到的日期字段值
another_date = record.your_odoo_date_field

# 对应需求的判断逻辑
if get_month_last_day("02/2020") < another_date:
    # 执行匹配的业务逻辑
    pass

if get_month_last_day("02/2021") < another_date:
    # 执行匹配的业务逻辑
    pass

注意:如果对接的是Odoo的 fields.Datetime 类型字段,需先用.date()方法提取纯日期部分再比较,避免时间戳干扰判断结果:

another_datetime = record.your_odoo_datetime_field
# 提取日期部分为date对象后再比较
another_date = another_datetime.date()

内容的提问来源于stack exchange,提问作者Ernesto Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 23:24:04