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

本文介绍了一种使用Python标准库中的calendar模块轻松获取指定月份天数的方法。通过调用monthrange函数,可以一次性获得一个月的第一天是周几以及该月的总天数,包括闰年的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值