Python中获取上月最后一天问题:月份返回0而非12的解决方法
解决Python中获取上月最后一天时月份变为0的问题
嘿,我太懂你遇到的这个坑了——直接对月份数字做减法,碰到1月的时候就会变成0,完全不符合咱们的日期逻辑!而且你原代码的思路还没处理不同月份的天数差异,比如1月有31天,2月可能是28或29天,直接硬写肯定会出问题。下面给你两个靠谱的解决方案,既能拿到当前日期,又能准确获取上月最后一天:
方法1:纯标准库实现(无需额外安装)
用datetime结合calendar模块,就能完美处理所有月份的边界情况,包括闰年:
import datetime import calendar # 获取当前日期,要是需要指定特定日期(比如你说的2018-01-25),就改成 datetime.date(2018, 1, 25) today = datetime.date.today() # 处理上月的年份和月份:1月的上月是去年12月 if today.month == 1: last_month_year = today.year - 1 last_month = 12 else: last_month_year = today.year last_month = today.month - 1 # calendar.monthrange 返回 (该月第一天是星期几, 该月总天数),取第二个值就是最后一天的日期 last_day_of_last_month = datetime.date( last_month_year, last_month, calendar.monthrange(last_month_year, last_month)[1] ) # 按需求输出格式 print(f"当前日期: {today.strftime('%Y-%m-%d')}") print(f"上月最后一天: {last_day_of_last_month.strftime('%Y-%m-%d')}")
测试一下你给的例子:
- 当
today是2018-01-25时,输出2018-01-25和2017-12-31; - 当
today是2018-02-25时,输出2018-02-25和2018-01-31; - 闰年场景比如
2020-03-01,会正确返回2020-02-29作为上月最后一天。
方法2:用第三方库简化代码(更简洁)
如果可以安装第三方库,python-dateutil的relativedelta能让代码更清爽,它会自动处理月份的跨年问题。另外还有个小技巧:本月第一天减1天就是上月最后一天,这个思路完全不用判断月份:
首先安装库:
pip install python-dateutil
然后写代码:
import datetime from dateutil.relativedelta import relativedelta today = datetime.date.today() # 或者指定日期:today = datetime.date(2018, 1, 25) # 先拿到本月第一天,减1天就是上月最后一天 first_day_of_current_month = datetime.date(today.year, today.month, 1) last_day_of_last_month = first_day_of_current_month - datetime.timedelta(days=1) # 输出结果 print(f"当前日期: {today.strftime('%Y-%m-%d')}") print(f"上月最后一天: {last_day_of_last_month.strftime('%Y-%m-%d')}")
这个方法是不是超简洁?而且完全不会有月份变0的问题,datetime会自动帮你处理年份的切换~
为什么你的原代码会出错?
你的原代码直接对time.strftime("%m")转成整数后减1,当月份是1时就会得到0,而0不是有效的月份值,自然会出问题。另外原代码里的(int(time.strftime("%d")))-1是想减一天,但这和你要的「上月最后一天」逻辑完全不符,所以得换思路才行哦~
内容的提问来源于stack exchange,提问作者Martin Bouhier
相关产品推荐
相关产品推荐

