如何计算提供日和月的星期几

2024-09-30 22:11:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这个计划严格规定在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]

Tags: fromanfordateisdeffunctioninteger
2条回答

Don't reinvent the wheel

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

Or as a number

^{pr2}$

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

如果您不能使用datetime,则可以这样做:

def day(d, m):
    day = (sum((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[:m-1]) + d + 3) % 7
#           ^                                                     ^      ^   ^  ^ ^
#           '   adding up the days in the months                |      |   |  | |
#                   up to but not including the current month   '      |   |  | |
#                                  plus the current day of the month   '   |  | |
#                                  and the day of the week on 12/31/2013   '  | |
#                    modulus (%) is what's left over after integer division   ' |
#                                                        seven days in a week   '

相关问题 更多 >