寻找时间差异

时间:2015-10-12 17:03:02

标签: python python-2.7 datetime

我正在用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'

我该如何解决这个问题?

2 个答案:

答案 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()