lundi 2 novembre 2020

Function to get a weekday from a date in Python

As part of a python tutorial, I've been trying to build a function that calculates the weekday from a given date. I know there's an easier way to do this but I really want to know why my function is not working. Whenever I enter a date, it returns None. I'd be grateful for any suggestions. Here's the code:

# check if year is leap year: division by 4 possible, division by 100 impossible unless division by 400 possible
def isYearLeap(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False


# calculate days in each month
def daysInMonth(year, month):
    if month == 9 or month == 4 or month == 6 or month == 11:
        return 30
    elif month == 2:
        if isYearLeap(year):
            return 29
        else:
            return 28
    elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
        return 31
    else:
        return False


# find out day of the year
def dayOfYear(year, month, day):
    century = year // 100
    # different rule for January and February because of leap years`enter code here`
    if month != 1 or month != 2:
        y = year % 100
        # Zeller's rule for calculating weekdays
        weekday = (day + (2.6 * (month - 2) - 0.2) - 2 * century + y + y / 4 + century / 4) % 7
        if weekday == 1:
            return "Sunday"
        elif weekday == 2:
            return "Monday"
        elif weekday == 3:
            return "Tuesday"
        elif weekday == 4:
            return "Wednesday"
        elif weekday == 5:
            return "Thursday"
        elif weekday == 6:
            return "Friday"
        elif weekday == 0:
            return "Saturday"
    else:
        y = (year % 100) - 1
        #Zeller's rule for calculating weekdays
        weekday = (day + (2.6 * (month + 10) - 0.2) - 2 * century + y + y / 4 + century / 4) % 7
        if weekday == 1:
            return "Sunday"
        elif weekday == 2:
            return "Monday"
        elif weekday == 3:
            return "Tuesday"
        elif weekday == 4:
            return "Wednesday"
        elif weekday == 5:
            return "Thursday"
        elif weekday == 6:
            return "Friday"
        elif weekday == 0:
            return "Saturday"


print(dayOfYear(2000, 12, 31))
print(dayOfYear(1980, 1, 4))

Aucun commentaire:

Enregistrer un commentaire