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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。