How to convert time python gives you to int

Here's my next 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)

      

An error is thrown when it hits line 17 (right 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'm terrible in python, but I need to know how I can change the time to an integer so that I can subtract it and get the time it took them to hit enter a second time. Thank you: D And I'm sorry aha

+3


source to share


3 answers


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 to use seconds as int then use print(int(diff))

+1


source


You can remove the call .time()

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 is like float



>>> time.total_seconds()
1.279208

      

If you just want the integer component of the past tense, you can use

>>> time.seconds
1

      

+4


source


end

and start

are objects datetime.time

, you cannot subtract them. If you want to subtract something, take one of the components, for example end.seconds - start.seconds

. Now that it works, since it will return seconds in a specific time, the seconds will close after 60 seconds, allowing you to win even if more than ten seconds have elapsed during reuse.

I would use time.time()

, which you can read about here: https://wiki.python.org/moin/WorkingWithTime . Basically every time it is called, it returns you the number of seconds that have passed since Jan 1, 1970. If you call this twice and subtract them, you get the time that has passed regardless of the current "real" time.

More information on time management in python can be found here: http://www.tutorialspoint.com/python/python_date_time.htm

+2


source







All Articles