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

jdatetime获取上月最后一天错误,显示上上月日期问题排查

问题描述

以下是我的代码:

import jdatetime
now = jdatetime.datetime.now()
end = now.strftime("%Y-%m-%d")
month = 12 if now.month == 1 else now.month - 1
year = now.year - 1 if now.month == 1 else now.year
first_day_of_last_month = now.replace(day=1, month=month, year=year)
last_day_of_last_month = first_day_of_last_month - jdatetime.timedelta(days=1)

其中first_day_of_last_month运行正常(示例值为01/10/1402),但last_day_of_last_month得到的是30/09/1402,而非预期的30/10/1402。请问我哪里出错了?

错误分析

你的核心逻辑颠倒了:

  • 你先算出上月的第一天(比如1402年10月1日),再减去1天,得到的必然是上上月的最后一天(1402年9月30日),这和你想要的「上月最后一天」完全不符。
  • 正确思路应该是:要么取当月第一天再减1天,要么取上月第一天后加一个月再减1天,才能得到上月的最后一天。

修正方案

方法一:当月第一天减1天(最简洁)

import jdatetime
now = jdatetime.datetime.now()
# 获取当月第一天
first_day_current = now.replace(day=1)
# 当月第一天减1天,即为上月最后一天
last_day_last_month = first_day_current - jdatetime.timedelta(days=1)

方法二:基于上月第一天调整

如果想保留「先获取上月第一天」的逻辑,可以这样修改:

import jdatetime
now = jdatetime.datetime.now()
month = 12 if now.month == 1 else now.month - 1
year = now.year - 1 if now.month == 1 else now.year
first_day_last_month = now.replace(day=1, month=month, year=year)

# 方式1:直接加一个月再减1天(自动处理月份天数差异)
try:
    next_month_first = first_day_last_month.replace(month=first_day_last_month.month + 1)
except ValueError:
    # 处理12月加1月的跨年情况
    next_month_first = first_day_last_month.replace(year=first_day_last_month.year + 1, month=1)
last_day_last_month = next_month_first - jdatetime.timedelta(days=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:40:15