如何在 Python 中获取月份中的天数
如果你想使用 Python 查找一个月有多少天,使用此代码片段:
days_in_month_basic.py
from calendar import monthrange
num_days = monthrange(2019, 2)[1] # num_days = 28
print(num_days) # 打印 28calendar 模块自动考虑闰年。
你也可以使用此函数代码片段:
days_in_month_function.py
from calendar import monthrange
def number_of_days_in_month(year=2019, month=2):
return monthrange(year, month)[1]
# 用法示例:
print(number_of_days_in_month(2019, 2)) # 打印 28你也可以使用 pip install -U UliEngineering 安装我的 Python3 库 UliEngineering,然后像这样导入使用 number_of_days_in_month():
uliengineering_import_example.py
from UliEngineering.Utils.Date import *Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow