技术生活

python实现一个星期几的函数

一、原理:

根据蔡勒公式(Zeller’s congruence)

For the Gregorian calendar

for the Julian calendar

二、python代码实现:

def get_day_of_week(day, month, year):
    """
    Arguments:
        day: int, 1~31
        month: int, 1~12
        year: int
    Returns:
        w: int, 0~6 represents Saturday(0), Sunday(1), Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6)
    """
    if not isinstance(day, int) or not isinstance(month, int) or not isinstance(year, int):
        raise Exception("invalid day, month or year!")
    if day > 31 or day < 1 or month > 12 or month < 1:
        raise Exception("invalid day or month!")

    # If January or February is entered you must add 12 to the month and minus 1 from the year. This puts you in month 13 or 14 of previous year.
    if month == 1 or month == 2:
        month += 12
        year -= 1

    J = (year // 100)
    K = (year % 100)

    m = month
    q = day

    day_of_week = (q + (13 * (m + 1) // 5) + K + (K // 4) + (J // 4) - 2 * J) % 7
    return day_of_week

引用:

https://en.wikipedia.org/wiki/Zeller%27s_congruence

发表评论

电子邮件地址不会被公开。 必填项已用*标注