在python中获取月份的最后一天
获取12月份的错误 ValueError:月份必须在1..12之内在python中获取月份的最后一天,python,date,Python,Date,获取12月份的错误 ValueError:月份必须在1..12之内 您不能将日期时间设置为13个月。所以你必须找到一种方法来修复它。一个简单的解决方案是将递增的月份转换为额外的年份: # 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
您不能将日期时间设置为13个月。所以你必须找到一种方法来修复它。一个简单的解决方案是将递增的月份转换为额外的年份:
# 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
作为当前月份传入,然后添加一个以获取下个月的,使其成为13
。检查12
案例并设置month=1
。在第3行month=cur\u ds.month+1
中,您给出的是无效的第13个月。若要计算给定月份的最后一天,还可以使用日历库中的月份范围
>>import calendar
>>year, month = 2016, 12
>>calendar.monthrange(year, month)[1]
31
我就是这样做的
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])
显然,如果月份是12月(12日),那么month=cur\u ds.month+1将是13日,对吗?很明显,13不是一个允许的月份,正如错误所说的那样?是的,除了使用if条件之外,我还有其他方法可以处理吗?你可以使用%12
,不是吗?哦,直接解决真正的问题。我赞成。向上投票。我总是忘记甚至存在。哈哈,这是我的日常生活,写一些东西,然后意识到有一个模块,可能更糟。可能已经存在,但您的旧代码库无法使用它。或者它是在你写完一个月后创建的。当2.7代码库需要能够廉价地缓存堆栈跟踪(以便在出现调试场景时可以稍后输出它们)时,我同时拥有了这两个功能。我基本上是在3.5发布前一个月发明的(当然,即使在那时我也不能使用StackSummary
,因为代码库是2.7,移动到3.x太痛苦了)。唉…:-)
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])