我需要找到如何通过另一个日期减去当前日期

时间:2018-02-23 22:48:32

标签: python

所以我试着制作一个剧本来告诉你你活了多久。它很好,但我无法找到如何从当前日期减去生日,如总变量中所示。

import time
## dd/mm/yyyy format
times=(time.strftime("%d/%m/%Y"))
day=(time.strftime("%d"))
month=(time.strftime("%m"))
year=(time.strftime("%Y"))
##questions
born_y=input('what year were you born')
born_m=input('what month')
born_d=input('what day')
##convert to decimal
current_time=int(year+'.'+month+'.'+day)
current_age=int(born_y+'.'+born_m+'.'+born_d)
##find age
total=current_time-current_age
print(total)

1 个答案:

答案 0 :(得分:1)

尝试使用datetime代替time,如下所示:

import datetime

year = input("What year were you born: ")
month = input("What month were you born: ")
day = input("What day were you born on: ") 

born = datetime.datetime(int(year), int(month), int(day))

age = datetime.datetime.now() - born

print(age.days)
>>> 7549

然后,您可以按照自己的意愿分割timedelta对象age,或者从age.days获取日期。

请注意,如果用户输入除整数之外的任何内容,则无法正常工作。