r/Python • u/LL_darkstrike29 • 2h ago
Resource Date calculator (en)
import datetime
def calculate_weekday(day, month, year):
"""
Calculates the day of the week for any date using the Doomsday Algorithm.
Returns a string with the day name in English.
"""
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
# 1. Check if the year is a leap year according to Gregorian rules
is_leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# 2. Identify the century anchor day (400-year cycle)
century_base = (year // 100) * 100
if century_base % 400 == 0:
century_anchor = 2 # Tuesday (e.g., years 2000, 1600)
elif century_base % 400 == 100:
century_anchor = 0 # Sunday (e.g., years 2100, 1700)
elif century_base % 400 == 200:
century_anchor = 5 # Friday (e.g., years 2200, 1800)
else:
century_anchor = 3 # Wednesday (e.g., years 1900, 2300)
# 3. Calculate the year component (Standard Doomsday Algorithm)
year_last_digits = year % 100
quotient_4 = year_last_digits // 4
year_doomsday = (century_anchor + year_last_digits + quotient_4) % 7
# 4. Map the monthly anchor dates
month_anchors = {
1: 4 if is_leap_year else 3, # January 4 (leap year) / January 3 (normal year)
2: 29 if is_leap_year else 28, # February 29 (leap year) / February 28 (normal year)
3: 14,
4: 4,
5: 9,
6: 6,
7: 11,
8: 8,
9: 5,
10: 10,
11: 7,
12: 12
}
# 5. Calculate the distance from the closest monthly anchor
current_anchor = month_anchors[month]
distance = day - current_anchor
# 6. Resolve the final day index (modulo 7)
final_day_index = (year_doomsday + distance) % 7
return days_of_week[final_day_index]
def validate_date(day, month, year):
"""Checks if a combination of day, month, and year is a valid real date."""
try:
datetime.date(year, month, day)
return True
except ValueError:
return False
if __name__ == "__main__":
print("=== USER INTERFACE ===")
print("Enter the dates you want to calculate. Type 'exit' to quit.\n")
while True:
try:
date_input = input("Enter date (DD/MM/YYYY): ").strip()
if date_input.lower() == 'exit':
print("Closing the program.")
break
# Parsing the user input
parts = date_input.split('/')
if len(parts) != 3:
raise ValueError
d = int(parts[0])
m = int(parts[1])
y = int(parts[2])
# Calendar validation
if not validate_date(d, m, y):
print("Error: The entered date does not exist (e.g., check leap years or month limits). Try again.\n")
continue
# Final calculation and output
result_day = calculate_weekday(d, m, y)
print(f"The date {date_input} corresponds to: {result_day}\n")
except ValueError:
print("Error: Invalid format. Please use exactly the DD/MM/YYYY format (e.g., 23/02/2016).\n")