user3049392
user3049392

Reputation: 1

How to get the difference between 2 datetimes in python?

import datetime

start = datetime.datetime.now()  
end = datetime.datetime.now()

enter = ""  
result = end - start  
alphabet = "abcdefghijklmnopqrstuvwxyz"  
print("Welcome to the alphabet game!")  
print("Try to type the alphabet as fast as you can!")  

enter = input("when you are ready type 'go' : ")  
if enter == "go":  
    start  
    print("GO")  
    g = input("")  
if g == alphabet:  
    print("Well done!")  
    print("Your time was: ", result)  

The problem is that the time it returns is just 00:00:00 how would I get the 2 datetimes to work within the code itself, or to record the time when the user has finished and started the input?
Any solutions?

Upvotes: 0

Views: 223

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121884

You set start and end just once, at the top. If you wanted to measure particular moments in time in your game, you need to call datetime.datetime.now() at that moment. Referring to start won't do that:

alphabet = "abcdefghijklmnopqrstuvwxyz"  
print("Welcome to the alphabet game!")  
print("Try to type the alphabet as fast as you can!")  
start = None

enter = input("when you are ready type 'go' : ")  
if enter == "go":  
    start = datetime.datetime.now()
    print("GO")  
    g = input("")  
if g == alphabet:
    if not start:
        print("We have yet to start!")
    else: 
        print("Well done!")
        print("Your time was: ", datetime.datetime.now() - start)  

Upvotes: 0

Sebastian Mach
Sebastian Mach

Reputation: 39089

Because you assign to result and end before letting the user play. Also, the start in the first if-body is meaningless.

Upvotes: 2

Related Questions