繁体   English   中英

在python中获取一个月的最后一天

[英]Get last day of month in python

12 月出现错误。

值错误:月份必须在 1..12

def last_day_of_month(ds):
    cur_ds = datetime.strptime(ds, '%Y-%m-%d')
    next_month = datetime(year=cur_ds.year, month=cur_ds.month+1, day=1)
    last_day_month = next_month - timedelta(days=1)
    return datetime.strftime(last_day_month, '%Y-%m-%d')

print last_day_of_month('2016-12-01')

在第 3 month=cur_ds.month+1您给出了无效的第 13 个月。 如果您想计算给定月份的最后一天,您还可以使用日历库中的月份范围。

>>import calendar
>>year, month = 2016, 12
>>calendar.monthrange(year, month)[1]
31

你不能用 13 个月来创建datetime时间。所以你必须找到一种方法来解决它。 一个简单的解决方案是将增加的月份转换为额外的年份:

# Reduce 12 to 1, 0 and all other #s to 0, #
extrayear, month = divmod(cur_ds.month, 12)
# Add 1 or 0 to existing year, add one to month (which was reduced to 0-11)
next_month = datetime(year=cur_ds.year + extrayear, month=month + 1, day=1)

您将12作为当前月份传递,然后添加一个以获得next_month ,使其成为13 检查12情况并改为设置month=1

我就是这样做的。

from django.utils import timezone
from calendar import monthrange
from datetime import datetime


current = timezone.now()
firstdayofmonth = current.replace(day=1)
endmonth = monthrange(current.year, current.month)
lastdayofmonth = datetime(current.year, current.month, endmonth[1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM