已知1900/01/01是星期一。(1)如果把1900/01/01當作第一天,请设计一个Python程序,計算2023/04/19是第幾日。(2)擴充(1)的Python程序的功能,讓用戶輸入1900/01/01至3000/12/31之間的任何有效日期,輸出該日期是1900/01/01之後的第幾日,以及當天是星期幾。
时间: 2023-07-05 18:19:53 浏览: 77
计算某日为星期几
以下是一个Python程序示例,可以实现上述功能:
```python
def is_leap_year(year):
"""
判断是否是闰年
"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def get_day_of_year(month, day, year):
"""
根据输入的月份和日期,计算DayofYear
"""
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
days_in_month[1] = 29
if month < 1 or month > 12:
return "Error: 月份输入错误!"
elif day < 1 or day > days_in_month[month - 1]:
return "Error: 日期输入错误!"
else:
day_of_year = sum(days_in_month[:month-1]) + day
return day_of_year
def get_day_of_week(day_of_year):
"""
根据DayofYear计算星期几
"""
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return days_of_week[(day_of_year - 1) % 7]
start_year = 1900
start_month = 1
start_day = 1
start_day_of_week = 0 # 1900/01/01是星期一,因此设置为0表示星期一
end_year = int(input("请输入年份:"))
end_month = int(input("请输入月份:"))
end_day = int(input("请输入日期:"))
# 计算1900/01/01至输入日期之间的总天数
total_days = 0
for year in range(start_year, end_year):
if is_leap_year(year):
total_days += 366
else:
total_days += 365
total_days += get_day_of_year(end_month, end_day, end_year) - get_day_of_year(start_month, start_day, start_year)
day_of_week = (start_day_of_week + total_days) % 7
print("输入的日期是1900/01/01之后的第{}天。".format(total_days))
print("当天是星期{}。".format(get_day_of_week(day_of_week)))
```
注:以上代码假设输入的年份为公历,且在1582年之后。在此例子中,输入的日期必须在1900/01/01至3000/12/31之间。
阅读全文