Search code examples
pythoncalendar

Easter change month


I need to print every Easter Sunday of 21st century. I need to determine the month: 4 (April) when the day d is no more than 30; if it's greater, then I need to convert that to the proper day in May. For instance, d=32 would be m=5, d=2 or May 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()

Solution

  • You have only one adjustment to make: if the day is more than 30, increment the month from April to May and reduce the day by 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)))
    

    Partial output, including the borderline cases:

    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.