T. Green
T. Green

Reputation: 321

Finding difference in time

I am creating a program in Python in which the user has to type the alphabet as quick as possible and then the computer outputs the time they took. My code so far is:

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

The programs has an error when working out the difference between the two times:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

How can I fix this?

Upvotes: 0

Views: 58

Answers (2)

Will Vousden
Will Vousden

Reputation: 33348

Arithmetic is not supported on Python's time type. Try using just the datetime instead:

first = datetime.now()
alph = raw_input('TYPE!!!')
second = datetime.now()

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90859

You cannot subtract datetime.time from datetime.time objects. It would be better to use datetime.now() (which contains both date and time components). Example -

first = datetime.now()
alph = raw_input('TYPE!!!')
second = datetime.now()

Upvotes: 2

Related Questions