GoldenPineapple1
GoldenPineapple1

Reputation: 53

How do I convert the time that python gives you into an int

Here is my following code:

from time import sleep
import datetime
print ("This is a game where you guess when 10 seconds have passed")
sleep (0.5)
input("Hit the enter key when you are ready")
start = datetime.datetime.now().time()
sleep (1)
print ("1")
sleep (1)
print ("2")
sleep (1)
print ("3...")
input
end = datetime.datetime.now().time()
time = (end) - (start)

There is an error when it gets to line 17 (Straight after it counts to 3) Here is the error:

Traceback (most recent call last):
  File "D:/Python/Scripts/Challenges/Challenge 6 - Time Guessing Game.py", line 17, in <module>
    time = (end) - (start)
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I apolagise that I am horrible at python but what i need to know is how i can change the time into an integer so that i can subtract it and get the time that it took them to press enter for the second time. Thank you :D And i'm sorry aha

Upvotes: 3

Views: 673

Answers (3)

Cory Kramer
Cory Kramer

Reputation: 117971

You can remove the .time() call from each, and it will work as expected

>>> start = datetime.datetime.now()
>>> end = datetime.datetime.now()
>>> time = end - start
>>> time
datetime.timedelta(0, 1, 279208)

And the time in seconds as a float

>>> time.total_seconds()
1.279208

If you just want the integer component of the elapsed time you can use

>>> time.seconds
1

Upvotes: 4

ShadowMitia
ShadowMitia

Reputation: 2533

end and start are datetime.time objects, you can't subtract them. If you want to substract something from them, take one of the components such as end.seconds - start.seconds. Now while this would work, since it returns the seconds in a certain time, does seconds will loop back after 60 seconds which would allow you to win even though in reallity it has been over ten seconds.

What I would use is time.time() which you can read more about here: https://wiki.python.org/moin/WorkingWithTime. Basically each time it's called it returns to you the number of seconds that has passed since the 1st of January 1970. If you call this twice twice and substract them you will get the time that has passed independantly of the current "real" time.

You can find more information about time management in python here: http://www.tutorialspoint.com/python/python_date_time.htm

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

You can just use time, you don't need datetime to just subtract seconds:

from time import sleep, time

print ("This is a game where you guess when 10 seconds have passed")
sleep (0.5)
input("Hit the enter key when you are ready")
start = time()
sleep (1)
print ("1")
sleep (1)
print ("2")
sleep (1)
print ("3...")
input()
end = time()
diff = end - start
print(diff)

If you want the seconds as an int use print(int(diff))

Upvotes: 1

Related Questions