我遇到python有关计算到下一个生日的时间长短的问题。这是我的代码:
import datetime
currentDate=datetime.date.today()
userInput=raw_input('please enter your birthday(dd/mm/yyyy)')
birthday = datetime.datetime.strptime(userInput,'%d/%m/%Y').date()
days=birthday-currentDate
print(days)
它给我回答的答案是-6930。
当它给我答案的时候,我试图把它分解成这样的部分:
import datetime
currentDate=datetime.date.today()
userInput=raw_input('please enter your birthday(dd/mm/yyyy)')
birthday = datetime.datetime.strptime(userInput,'%d/%m/%Y').date()
months =birthday.month-currentDate.month
days = birthday.day-currentDate.day
print('your next birthday is in ' +str(months) +' months and '+ str(days) + 'days' )
然后可以输入月份等于或大于当月,所以当我输入时输入:18/09/1996它给出了答案“你的下一个生日是2个月和9天“但是如果输入的月份小于当前月份:18/05/1996它给我回答的答案是”旅游生日是-2个月和9天“
希望你能帮助我:)。答案 0 :(得分:1)
要获取下一个生日的日期,获取月份和月份之间的差异是不够的。
首先,将生日转移到今年;你可能想要处理闰年:
birthday = datetime.datetime.strptime(userInput, '%d/%m/%Y').date()
today = datetime.date.today()
try:
next_birthday = birthday.replace(year=today.year)
except ValueError:
# oops, not a leapyear this year, no february 29th; use the day before
next_birthday = birthday.replace(day=28, year=today.year)
if next_birthday < today: # already passed this year, pick next year
try:
next_birthday = birthday.replace(year=today.year + 1)
except ValueError:
# oops, not a leapyear next year, no february 29th, use the day before
next_birthday = birthday.replace(day=28, year=today.year + 1)
difference = next_birthday - today
months, days = divmod(difference.days, 30) # assume 30 days per month
print 'Your birthday is in about {} months and {} days'.format(months, days)
答案 1 :(得分:0)
您是否可以执行以下操作?:
如果它大于当年的生日月/日,则从你的生日NEXT年中减去当前日期。
否则,您今年的生日没有到来,所以从今年的生日中减去当前日期。