我们如何确定python中给定月份的天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4938429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:15:22  来源:igfitidea点击:

How do we determine the number of days for a given month in python

python

提问by Joel James

I need to calculate the number of days for a given month in python. If a user inputs Feb 2011 the program should be able to tell me that Feb 2011 has 28 days. Could any one tell me which library I should use to determine the length of a given month.

我需要在 python 中计算给定月份的天数。如果用户输入 2011 年 2 月,程序应该能够告诉我 2011 年 2 月有 28 天。谁能告诉我应该使用哪个图书馆来确定给定月份的长度。

采纳答案by Andrew Hare

Use calendar.monthrange:

使用calendar.monthrange

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)

Just to be clear, monthrangesupports leap years as well:

需要明确的是,也monthrange支持闰年:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

As @mikhail-pyrev mentions in a comment:

正如@mikhail-pyrev 在评论中提到的:

First number is weekday of first day of the month, second number is number of days in said month.

第一个数字是该月第一天的工作日,第二个数字是该月的天数。

回答by Bj?rn Lindqvist

Alternative solution:

替代解决方案:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

回答by Frosty Snowman

Just for the sake of academic interest, I did it this way...

只是为了学术兴趣,我是这样做的……

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day