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


Python calendar weekday()用法及代碼示例


Python calendar.weekday() 方法

weekday() 方法是 Python 中日曆模塊的內置方法。它適用於簡單的文本日曆,並返回函數參數中提到的給定年、月和日的星期幾。此處星期一表示 0 並在接下來的日子裏為年(1970-…)、月(1-12)、日(1-31)加一。

模塊:

    import calendar

用法:

    weekday(year, month, day)

參數:

  • year: 必選參數,代表日曆的年份值
  • month: 必選參數,代表日曆的月份值
  • day: 必選參數,代表月份中的第幾天。

返回值:

這個方法的返回類型是<class 'int'>,它返回一個數字,它是給定年、月和日的日期。星期一是 0,星期日是 6。

例:

# Python program to illustrate the 
# use of weekday() method
  
# importing calendar module 
import calendar 

year = 2020
month = 2
day = 20
x = calendar.weekday(year, month, day)
print("Weekday number for the given date:", x)
print()

# We can also make a list of days and 
# print the day name accordingly
wday = ['Monday', "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
year = 1996
month = 10
day = 27
x = calendar.weekday(year, month, day)
print("Weekday number:", x)
print("Weekday name:", wday[x])

輸出

Weekday number for the given date:3

Weekday number:6
Weekday name:Sunday

注意:函數參數中的日期應該是有效的,否則會引發 ValueError。

例如,如果您打印 31 September 2019,這將是錯誤的,因為 9 月隻有 30 天。

例:

# Python program to illustrate the 
# use of weekday() method
  
# importing calendar module 
import calendar 

year = 2019
month = 2
day = 29

x = calendar.weekday(year, month, day)

print("Weekday number for the given date:", x)

print()

輸出

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    x = calendar.weekday(year, month, day)
  File "/usr/lib/python3.8/calendar.py", line 117, in w
eekday
    return datetime.date(year, month, day).weekday()
ValueError:day is out of range for month


相關用法


注:本文由純淨天空篩選整理自 Python calendar Module | weekday() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。