复活节换月

2024-04-24 11:20:04 发布

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

我需要在21世纪的每个复活节星期天印刷。我需要确定月份:4(四月),当日期d不超过30;如果它更大,那么我需要将其转换为5月份的适当日期。例如,d=32将是m=5, d=2或5月2日。你知道吗

import calendar
import datetime


def easter():
    for y in range(2001, 2101):
        m2 = 2 * (y % 4)
        m4 = 4 * (y % 7)
        m19 = 19 * (y % 19)
        v2 = (16 + m19) % 30
        v1 = (6 * v2 + m4 + m2) % 7
        p = v1 + v2
        d = 3 + p
        print ('Easter Sunday for the year', y, 'is',
               datetime.date(2015, m, 1).strftime('%B'),
               '{}.'.format(int(d)))


easter()

Tags: inimportfordatetimedefcalendarv2v1
1条回答
网友
1楼 · 发布于 2024-04-24 11:20:04

你只需要做一个调整:如果一天超过30天,增加从4月到5月的月份,减少30天:

    if d <= 30:
        m, d = 4, d
    else:
        m, d = 5, d-30

    print("Easter Sunday for the year", y, "is",
          datetime.date(y, m, d).
             strftime('%B'), '{}.'.format(int(d)))

部分输出,包括临界情况:

Easter Sunday for the year 2073 is April 30.
Easter Sunday for the year 2074 is April 22.
Easter Sunday for the year 2075 is April 7.
Easter Sunday for the year 2076 is April 26.
Easter Sunday for the year 2077 is April 18.
Easter Sunday for the year 2078 is May 8.
...
Easter Sunday for the year 2088 is April 18.
Easter Sunday for the year 2089 is May 1.

相关问题 更多 >