Skip to main content
 首页 » 编程设计

python之如何在提供日期和月份的情况下计算星期几

2025年05月04日14cyq1162

这个程序严格设定在 2014 年。但是,我想知道我的方向是否正确。这是我目前所拥有的:

def day(d,m): # Function for determining day name for a given date. 
    """Where m is an integer from 1 through 12 expressing a month, and d is an integer from  
    1 through 31 expressing the day-part of a date in 2014.""" 
 
    day = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] 
    weekday = (d + (2.6*m - 0.2) -2*20 + 2014 + (2014//4) + (20//4)) 
    return day[weekday] 

请您参考如下方法:

Don't reinvent the wheel :

>>> import datetime 
>>> datetime.datetime(2014, 2, 16).strftime('%a') 
'Sun' 

Or as a number :

>>> import datetime 
>>> datetime.datetime(2014, 2, 16).weekday() 
6 

然后您可以将其传递到您的 day 列表中