我是python编程的新手,我的编码有问题,因为输出不能在几天和几秒内正确显示年龄(如下面'输出'所示)
Please enter your birthday
Year:1985
Month (1-12):5
Date:8
Your age is 10024 days, 0:00:00
任何人都可以进一步协助解决此问题的原因和解决方法吗?
print "Please enter your birthday "
bd_y=int(input("Year:"))
bd_m=int(input("Month (1-12):"))
bd_d=int(input("Date:"))
from datetime import date
now = date.today ()
age = date(int(bd_y), int(bd_m), int(bd_d))
print ("Your age is " + str(now-age))
提前致谢:)
答案 0 :(得分:7)
datetime.date
仅跟踪年,月和日。如果你想要时间,你应该使用datetime.datetime
:
>>> from datetime import datetime
>>> str(datetime.now() - datetime(1985, 5, 8))
'10024 days, 8:51:08.441714'
减法的结果是datetime.timedelta
对象,其中包含用于自定义输出的属性days
,seconds
和microseconds
:
>>> delta = datetime.now() - datetime(1985, 5, 8)
>>> print "Your age is %d days and %d seconds" % (delta.days, delta.seconds)
Your age is 10024 days and 32125 seconds
答案 1 :(得分:5)
您应该使用datetime
代替date
。
确保您也更改了导入。
答案 2 :(得分:2)
以下作品。你被转换为int()两次,但这不会破坏它。
我建议按照建议切换到日期时间,但下面是使用您提供的内容。
print "Please enter your birthday"
bd_y = input("Year: ")
bd_m = input("Month (1-12): ")
bd_d = input("Date: ")
from datetime import date
now = date.today()
birthdate = date(int(bd_y), int(bd_m), int(bd_d))
age = now-birthdate
print "Your age is %s" % age
答案 3 :(得分:1)
print("please enter your birthday")
bd_y=int(input("Year:"))
bd_m=int(input("Month(1-12):"))
bd_d=int(input("Date:"))
from datetime import date
now = date.today ()
age = date(int(bd_y),int(bd_m), int(bd_d))
print ("your age is " +str(now-age))