In: Computer Science
PYTHON PROGRAM: Write a program that determines the day of the week for any given calendar date after January 1, 1900, which was a Monday. This program will need to account for leap years, which occur in every year that is divisible by 4, except for years that are divisible by 100 but are not divisible by 400. For example, 1900 was not a leap year, but 2000 was a leap year.
The basic idea to find the day of the week is to find the total number of days that have passed since the given date and then taking the modulo with 7. This would give us the index of the day of the week.
Python code for this:
# check if its a leap year
# If a year is leap, it is divisible by 4 but not by 400
def is_leap(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
return False
# Checking how many days have passed since 1 January 1990
def days_since(date, month, year):
n1 = 1990 * 365 + 1 # days of 1 January 1990 from 00/00/0000
n1 += int(1990 / 4 - 1990 / 100 + 1990 / 400)
# calculating days of given date from 00/00/0000
n2 = year * 365 + date
for i in range(0, month - 1):
n2 += monthDays[i]
years = year
if month <= 2:
years -= 1
n2 += int(years / 4 - years / 100 + years / 400)
# Returning the difference of the 2 dates
return n2 - n1
# Printing the day of the week
def week_day(date, month, year):
days = days_since(date, month, year)
print(days_of_week[days % 7])
# creating 3 lists: monthDays that has number of days in each month
# days_of_week: stores the name of days in week
# months: stores the mane of the months
monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"]
# taking user input for the date after 1 january 1990
date, month, year = map(int, input("Enter the date in format:DD MM YYYY: ").split())
# printing the day of the week the given date is
print("{} {} {} is a ".format(date, months[month - 1], year), end="")
week_day(date, month, year)
Screenshot for reference:
Screenshot of output: