Home > Software engineering >  Trying to use Zeller’s formula to return days of the week using python
Trying to use Zeller’s formula to return days of the week using python

Time:03-14

I see java codes but can't fully compare them with python. I am trying to use the Zeller’s Congruence to find the day of the week for any date.

Zeller’s formula assumes that for each computation within the formula where there is a quotient (or a division of two numbers), the integer value of that computation is used. If the month is January or February then 12 is added to the month and 1 subtracted from year before calculating day. day = (((13*m 3) / 5 d y (y / 4) - (y / 100) (y / 400)) %7).

day_names =[('Monday'),'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

for example day_names[0] = 'Monday' and day_names[6] = 'Sunday'

The below does not seem to ever give me the correct dates, is there anyone who might be able to tell what I am doing wrong if not everything?

def day_of_week1(d, m, y):
    d=1<=d<=31
    m=1<=m<=12
    y=1<=y<=10**5
    if m in range (1,2):
        m=m 12
        y=y-1
    day_names =[('Monday'),'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
    day =(((13*m 3) / 5   d   y   (y / 4) - (y / 100)   (y / 400)) %7)
    day=(math.ceil(day))
    if 2>day>=1:
        return day_names[0]
    elif 3>day>=2:
        return day_names[1]
    elif 4>day>=3:
        return day_names[2]
    elif 5>day>=4:
        return day_names[3]
    elif 6>day>=5:
        return day_names[4]
    elif 7>day>=6:
        return day_names[5]
    elif 8>day>=7:
        return day_names[6]

CodePudding user response:

Use the day names from the calendar module. Also, the adjustment for the month is not compliant with Zeller's Rule. Try this:

import calendar

def day_of_week(d, m, y):
    if m < 3:
        y -= 1
        m  = 10
    else:
        m -= 2
    yc, yd = divmod(y, 100)
    r = d   (13 * m - 1) // 5   yd   yd // 4   yc // 4 - 2 * yc
    return calendar.day_name[r % 7 - 1]

print(day_of_week(9, 11, 1951))

Output:

Friday
  • Related