我正在用Python创建一个程序,用户必须尽快输入字母,然后计算机输出他们所花费的时间。到目前为止我的代码是:
import sys
from datetime import *
ready = raw_input('Press enter when ready')
first = datetime.now().time()
alph = raw_input('TYPE!!!')
second = datetime.now().time()
if alph != 'abcdefghijklmnopqrstuvwxyz':
print 'Inocrrect!'
sys.exit()
else:
time = second - first
print 'It took you', time.seconds
在计算两次之间的差异时程序出错:
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
我该如何解决这个问题?
答案 0 :(得分:2)
您无法从datetime.time
个对象中减去datetime.time
。最好使用datetime.now()
(包含日期和时间组件)。示例 -
first = datetime.now()
alph = raw_input('TYPE!!!')
second = datetime.now()
答案 1 :(得分:1)
Python time
类型不支持算术运算。请尝试仅使用datetime
:
first = datetime.now()
alph = raw_input('TYPE!!!')
second = datetime.now()