对于我的学校项目,我必须制作一个python脚本,告诉用户他们达到100岁之前的多少年,以及他们下一个生日的天数。我已经想到了第一个问题,但我不知道如何解决这个项目的第二部分。总结:如何在Python(3.2)上获得用户下一个生日的日子。 这就是我到目前为止所做的:
from datetime import datetime
name = input("What's your name?")
print("Nice to meet you %s." % (name))
print("What day is your birthday? (MMDDYYYY)")
birthdate = input()
birthday = int(birthdate[2:3])
birthyear = int(birthdate[4:])
print (birthyear)
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
currentAge = current_year - birthyear
age = current_year - birthyear
print (now)
print (age)
year_till_100 = str(100 - currentAge)
print ("You will be 100 in %s years." % (year_till_100))
答案 0 :(得分:2)
以下是具有任意日期的基本示例:
>>> import datetime as dt
>>> diff = dt.datetime(2017, 1, 1) - dt.datetime.now()
>>> diff.days
52
>>>
在你的情况下,差异将是这样的:
diff = dt.datetime(birthyear+1, int(birthdate[0:2]), birthday) - now
# ^^^ your birthmonth
答案 1 :(得分:0)
这可行,而不是最佳解决方案。
from datetime import date
born = '06151995'
yearInt = int(born[-4:])
dayInt = int(born[2:4])
monthInt = int(born[0:2])
d0 = date(yearInt, monthInt, dayInt)
d1 = date(yearInt + 100, monthInt, dayInt)
delta = d1 - d0
print delta.days
编辑: 这是他们出生后多少天。
答案 2 :(得分:0)
一些建议,
birthday = int(birthdate[2:3])
只是从birthdate
字符串输入切一个数字,应该包括2位数天:
birthday = int(birthdate[2:4]
同样,您需要一个出生月份来确定下一个生日的天数:
birthmonth = int(birthdate[0:2])
现在你已经拥有了计算下一个生日前几天所需的所有组件:
days_til_next_bd = datetime(current_year+1, birthmonth, birthday) - datetime.now()
print ("%s days until your next birthday." % days_til_next_bd.days)
演示:
你的生日是哪天? (MMDDYYYY)
09112001
你将在85年内100岁 到你下一个生日的305天。