使用python中的zellers一致性计算星期几

    科技2026-10-06  2

    In this post I’ll write an implementation in Python of Zeller’s Congruence, a simple and elegant little formula to carry out the seemingly complex task of calculating the day of the week (Monday, Tuesday etc.) from a date.

    在这篇文章中,我将用Zeller的Congruence用Python编写一个实现,这是一个简单优雅的小公式,可以执行看似复杂的任务,该任务从日期开始计算星期几(星期一,星期二等)。

    克里斯蒂安·泽勒(Christian Zeller)和他的聪明小公式 (Christian Zeller and His Clever Little Formula)

    The formula was developed by German mathematician Christian Zeller (24 June 1822, a Monday, to 31 May 1899, a Wednesday). I have always been impressed that a task which you might think highly complex and solvable only by some sort of brute-force iteration can actually be reduced to a short and elegant formula. Of course you wouldn’t use the code in this post in production applications as Python provides the functionality already, but I hope you agree it is a worthwhile programming exercise.

    该公式由德国数学家克里斯蒂安·泽勒(Christian Zeller)(1822年6月24日,星期一,至1899年5月31日,星期三)开发。 我一直给我留下深刻的印象,您可能认为仅通过某种蛮力迭代就可以高度复杂且可解决的任务实际上可以简化为简短而优雅的公式。 当然,由于Python已经提供了该功能,因此您不会在生产应用程序中使用本文中的代码,但是我希望您同意这是值得进行的编程练习。

    There are several versions of the formula, including two sub-versions of each, one for the Gregorian calendar and one for the Julian. This is the Gregorian version of the formula I will be implementing, in an image stolen from Wikipedia.

    该公式有多个版本,每个版本包含两个子版本,一个用于格里高利历,一个用于朱利安。 这是我将要实现的公式的公历版本,该图片是从Wikipedia窃取的图像。

    Note that the symbols like an elongated letter L and it’s mirror-image twin denote “floor”, ie the result of the term is rounded down to the nearest integer. The full Wikipedia article is here and is worth at least skimming.

    请注意,像拉长的字母L这样的符号及其镜像双像表示“底”,即,该项的结果四舍五入到最接近的整数。 完整的Wikipedia文章在这里,至少值得一读。

    Rewritten in a more computer-friendly way we get:

    以更友好的计算机方式进行重写,我们得到:

    开始编码 (Starting to Code)

    The project consists of these files which you can clone/download from Github.

    该项目包含这些文件,您可以从Github克隆/下载这些文件。

    zeller.py

    zeller.py main.py

    main.py

    This is the first part of zeller.py.

    这是zeller.py的第一部分。

    import datetime import random import calendar import math def showdatesanddays(): """ Creates a selection of random dates and runs the Zeller Algorithm on them, printing out the date, and then the day according to Python and Zeller. """ # Zeller gives a value 0 to 6 representing Saturday to Friday zellerdays = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] for i in range(0, 19): d = datetime.date.fromtimestamp(random.randint(1, 1000000000)) print("Date: " + str(d)) print("Python: " + calendar.day_name[d.weekday()]) print("Zeller: " + zellerdays[zellergregorian(d)]) print("------------------")

    The showdatesanddays function firstly creates a list of day names starting with Saturday. These correspond with the values returned by Zeller’s Algorithm. We need to do this as “Python Weeks” start on a Monday.

    showdatesanddays函数首先创建一个以星期六开始的日期名称列表。 这些与Zeller算法返回的值相对应。 我们需要这样做,因为“ Python周”从星期一开始。

    After that we enter a for loop which generates a number of random dates using the fromtimestamp and randint functions. The fromtimestamp function creates a date from the number of seconds from 1/1/1970, and using 1 billion as the upper limit of randint will create dates between 1/1/1970 and 9/9/2001, which is adequate to demonstrate the algorithm.

    之后,我们进入一个for循环,该循环使用fromtimestamp和randint函数生成许多随机日期。 fromtimestamp函数从fromtimestamp 1月1日开始的秒数创建日期,使用10亿作为randint的上限将创建1/1/1970到9/9/2001之间的日期,这足以证明算法。

    After that we just need to print out the date and the corresponding day name using Python’s calendar.day_name list. Finally we print out the day name again from the zellerdays list, using a call to our zellergregorian function as the list index.

    之后,我们只需要使用Python的calendar.day_name列表打印日期和相应的日期名称即可。 最后,我们通过调用zellergregorian函数作为列表索引,再次从zellerdays列表中打印出日期名称。

    We can now implement that function:

    我们现在可以实现该功能:

    def zellergregorian(d): """ Runs the Zeller algorithm on the given date and returns the day index 0 to 6 for Saturday to Friday. """ q = d.day m = d.month Y = d.year # adjust month to run from 3 to 14 from March to February if m <= 2: m+= 12 # and also adjust year if January or February if d.month <= 2: Y -= 1 h = (q + math.floor((13 * (m + 1)) / 5) + Y + math.floor(Y / 4) - math.floor(Y / 100) + math.floor(Y / 400)) % 7 return h

    In zellergregorian we first declare three variables for day, month and year, setting them to the values from the date function argument. Of course we could just use the values in the date directly but I wanted to use variable names in the formula which matched those used by Herr Zeller. (I don’t know why day is called “q”!)

    在zellergregorian我们首先为日,月和年声明三个变量,并将它们设置为date函数参数中的值。 当然,我们可以直接使用日期中的值,但我想在公式中使用与Zeller先生使用的变量名称匹配的变量名称。 (我不知道为什么一天被称为“ q”!)

    We then need to adjust month and year if the month of our date is January or February as the algorithm uses years running from March to February, indexed 3 to 14.

    然后,如果我们的日期的月份是一月或二月,则需要调整月份和年份,因为该算法使用的是从三月到二月的年份,索引为3到14。

    Finally we calculate the day index — if you examine this line carefully you will see it implements the algorithm given above exactly. Note the use of the math.floor function to round down various terms to the nearest integer.

    最后,我们计算日指数-如果您仔细检查此行,您会看到它完全实现了上面给出的算法。 请注意使用math.floor函数将各种术语四舍五入为最接近的整数。

    In main.py and after a line to print the heading we call showdatesanddays.

    在main.py中,在一行打印标题之后,我们将其称为showdatesanddays.

    import zeller def main(): """ Zeller's Congruence calculates the day of the week from the given date. """ print("-----------------------------------") print("| codedrome.com |") print("| Zeller's Congruence: |") print("| Calculating the Day of the Week |") print("-----------------------------------") zeller.showdatesanddays() main()

    Now we can run the program with this command…

    现在我们可以使用此命令运行程序了……

    python3.8 main.py

    python3.8 main.py

    …which will give us this output.

    ……这将为我们提供输出。

    You will be pleased to see that Python and Zeller days are the same for all dates.

    您会很高兴看到Python和Zeller的日期在所有日期都是相同的。

    翻译自: https://medium.com/explorations-in-python/calculating-the-day-of-the-week-with-zellers-congruence-in-python-8009001dd84e

    相关资源:python日期时间运算
    Processed: 0.009, SQL: 9