gpt4 book ai didi

python - 如何查询当月的天数

转载 作者:IT老高 更新时间:2023-10-28 22:07:10 25 4
gpt4 key购买 nike

Possible Duplicate:
Get Last Day of the Month in Python

如何获取当月的天数?即,如果当前月份是“2012 年 1 月”,我应该得到 31。如果是“2012 年 2 月”,我应该得到 29。

最佳答案

正如彼得所说,calendar.monthrange(year, month) 返回year 的工作日(0-6 ~ Mon-Sun)和天数(28-31) >, .

>>> import calendar
>>> print calendar.monthrange(2012,1)[1]
31
>>> calendar.monthrange(2012,2)[1]
29

编辑:更新答案以返回当月的天数

>>> import calendar
>>> import datetime
>>> now = datetime.datetime.now()
>>> print calendar.monthrange(now.year, now.month)[1]
29

关于python - 如何查询当月的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9481136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com