在Python中获取本月的最后一天 [英] Get Last Day of the Month in Python
问题描述
有没有办法使用Python的标准库来轻松确定(即一个函数调用)给定月份的最后一天?
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?
如果标准库不支持,dateutil包支持这个?
If the standard library doesn't support that, does the dateutil package support this?
推荐答案
我以前没有注意到,当我看着日历模块的文档,但是一种名为 monthrange 提供此信息:
I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:
月份(年,月)
返回指定年份的月份第一天的工作日和月份的天数和月份。
monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.
>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)
so: p>
so:
calendar.monthrange(year, month)[1]
似乎是最简单的方式。
只需要清楚, monthrange
支持闰年:
Just to be clear, monthrange
supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
我以前的答案仍然有效,但显然不是最佳的。
My previous answer still works, but is clearly suboptimal.
这篇关于在Python中获取本月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!