📜  zeller year - Python (1)

📅  最后修改于: 2023-12-03 15:21:23.010000             🧑  作者: Mango

Zeller Year - Python

The Zeller Year algorithm is a way to calculate the day of the week for any given date. This algorithm was devised by Christian Zeller in the 19th century. In this article, we will discuss how to implement the Zeller Year algorithm in Python.

The Algorithm

The Zeller Year algorithm is based on the following formula:

h = (q + ((13 * m - 1) / 5) + K + (K / 4) + (J / 4) - 2J) mod 7

Where:

  • h is the day of the week (0 = Saturday, 1 = Sunday, ..., 6 = Friday)
  • q is the day of the month (1 to 31)
  • m is the month (3 = March, 4 = April, ..., 14 = February)
  • K is the year of the century (year mod 100)
  • J is the century (year / 100)

Note: In this algorithm, January and February are considered to be the 13th and 14th month of the previous year, respectively. For example, January 2022 would be considered as January 2021.

Implementation

Here's the Python code that implements the Zeller Year algorithm:

def zeller_year(day, month, year):
    if month < 3:  # January and February are considered to be the 13th and 14th month of the previous year
        month += 12
        year -= 1

    K = year % 100
    J = year // 100

    h = (day + ((13 * (month + 1)) // 5) + K + (K // 4) + (J // 4) - 2 * J) % 7

    return h

To use this function, simply call it with the day, month, and year as arguments, like this:

>>> zeller_year(22, 7, 2021)
4

This means that July 22, 2021 is a Thursday (since 4 corresponds to Thursday in the algorithm).

Conclusion

The Zeller Year algorithm is a useful tool to calculate the day of the week for any given date. In Python, implementing this algorithm is easy and straightforward. By understanding this algorithm, you can create more advanced date-related applications or solve coding challenges related to calculating the day of the week.