为什么此代码返回的年份错误?

圣诞老人

我写这个脚本只是为了练习,由于某种原因,在客户输入他们的出生年份后返回的年份存在问题。例如,我的朋友出生于 1991 年,但出生于 10 月。该代码在 1 月运行良好,但对于 10 月,它指出那年(1991 年)的 NYE 是 1992 年我朋友的生日(1991 年 10 月 13 日)。请指教!

我尝试阅读手册一年,但没有太多提供。我用谷歌搜索,但这个问题很模糊。

from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

today = date.today() # date.var returns date
print '\nToday is', (today.strftime('%B')), (today.strftime('%d')), (today.strftime('%Y')) # time formats used to return mo, day, yr

print "\nHello! What is your name?"
user_name = raw_input('--> ')
print '\nHow old are you, %s?' % user_name
user_age = int(raw_input('--> '))

# Python lists start with 0 index so add in a dummy for 0
months = ['Dummy', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
print '\nWhat day, month and year were you born?'
user_day = int(raw_input('Day: ')) # use this line to get index from months list
user_month = months.index(raw_input('Month: '))
user_year = int(raw_input('Year: ')) 
date_birth = user_year, user_month, user_day

print '\nYou were born on', date_birth

NYE_birth = (today.year - user_age, 1, 1)
print 'The New Year\'s Eve of that year was ', NYE_birth
print 'You were born', user_month - 1, 'months and', user_day - 1, 'days after NYE.\n'

# need to include months

ry = 100 - user_age
age_cent = date (int(today.year + ry), int(user_month), int(user_day))
print '\nWow, a long way to go! You will turn 100 years-old on',  age_cent
print '\n'

预期结果应该是 NYE 与用户的出生年份相同。但它显示第二年。

巴马

你的朋友是1991年10月出生的,到现在才27岁,下个生日就28岁了。当您从当前年份中减去 27 时,就是 1992 年。

如果生日晚于您运行程序的那一年,您需要减去一个额外的年份来说明这一点。

if today.month > user_month or (today.month == user_month and today.day >= user_day):
    NYE_birth = (today.year - user_age, 1, 1)
else:
    NYE_birth = (today.year - user_age - 1, 1, 1)

您需要对世纪年进行类似的调整。

当然,既然你问他们是哪一年出生的,你可以user_year不从年龄来计算。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章