python获取上个月最后一天_在Python中获取本月的最后一天

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:09   1893   0

Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

解决方案

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:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

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.

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP