仅使用基本的Python包
基于"没有特殊的包"这一前提,您可以使用datetime.timedelta
来解决此类问题:
import datetime
start_date = datetime.datetime(year=2008, month=5, day=19)
end_date = start_date + datetime.timedelta(days=10000)
print(end_date.date())
没有任何基础包(并继续解决问题)
即使是绕过基本的Python包,按照以下方式进行处理应该会有所帮助(我希望如此!)。
首先定义一个函数来确定一年是否为闰年:
def is_it_a_leap_year(year) -> bool:
"""
Determine if a year is a leap year
Args:
year: int
Extended Summary:
According to:
https://airandspace.si.edu/stories/editorial/science-leap-year
The rule is that if the year is divisible by 100 and not divisible by
400, leap year is skipped. The year 2000 was a leap year, for example,
but the years 1700, 1800, and 1900 were not. The next time a leap year
will be skipped is the year 2100.
"""
if year % 4 != 0:
return False
if year % 100 == 0 and year % 400 != 0:
return False
return True
然后定义一个函数来确定一个人的年龄(利用上述内容来识别闰年):
def age_after_n_days(start_year: int,
start_month: int,
start_day: int,
n_days: int) -> tuple:
"""
Calculate an approximate age of a person after a given number of days,
attempting to take into account leap years appropriately.
Return the number of days left until their next birthday
Args:
start_year (int): year of the start date
start_month (int): month of the start date
start_day (int): day of the start date
n_days (int): number of days to elapse
"""
start_pre_leap = (is_it_a_leap_year(start_year) and start_month < 3)
if start_month == 2 and start_day == 29:
start_pre_leap = False
age = 0
current_year = start_year
days_left = n_days
while days_left > 364:
if is_it_a_leap_year(current_year):
if age > 0:
days_left -= 366
elif age == 0 and not start_pre_leap:
days_left -= 365
else:
days_left -= 366
else:
days_left -= 365
if days_left >= 0:
age += 1
current_year += 1
return age, days_left
使用您的示例,您可以通过以下方式测试该函数:
age, remaining_days = age_after_n_days(start_year=2000, start_month=5, start_day=19, n_days=10000)
现在您已经知道了完整年份和剩余天数,您可以使用剩余天数来计算确切的日期。
sum
作为自己的变量名。您可能会注意到它在代码中出现时显示为不同的颜色:这是因为它是Python中内置函数的名称。在Python中掩盖内置函数的名称是令人困惑的,甚至可能产生意外后果。 - Stef