当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python calendar monthrange()用法及代码示例


Python calendar.monthrange() 方法

monthrange() 方法是 Python 中日历模块的内置方法。它适用于简单的文本日历并返回一个元组,其中第一个值是该月第一天的工作日,第二个值是指定年份和月份的月份中的天数。

模块:

    import calendar

用法:

    monthrange(year, month)

参数:

  • year:它是一个必需参数,代表日历的年份。
  • month:它是一个必需参数,代表日历的月份。

返回值:

这个方法的返回类型是<class 'tuple'>,其中第一个值是该月第一天的工作日数,第二个值是该月的天数。

例:

# Python program to illustrate the 
# use of monthrange() method

# importing calendar module
import calendar

year = 2020
month = 4

print("The first weekday number of the April 2020 and number of days in April:", calendar.monthrange(year, month))
print()
# Prints (2, 30) where 2 is the first 
# weekday number and 30 is the number of days in April

# We can store the values separately
year = 2010
month = 10
x, y = calendar.monthrange(year, month)
print("First weekday number:", x)
print("Number of days in this month:", y)
print()

# We can also print the WEEKDAY name
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
year = 2019
month = 12
x, y = calendar.monthrange(year, month)
print("First weekday number", x)
print("Number of days in this month:", y)
print("Weekday was:", days[x])
print()

输出

The first weekday number of the April 2020 and number of days in April:(2, 30)

First weekday number:4
Number of days in this month:31

First weekday number 6
Number of days in this month:31
Weekday was:Sunday


相关用法


注:本文由纯净天空筛选整理自 Python calendar Module | monthrange() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。