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
相关产品推荐
相关产品推荐

