當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。