如何在python中获得2个日期时间的区别?

时间:2013-11-29 12:36:46

标签: python datetime

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)  

问题是它返回的时间只是00:00:00 如何让2个日期时间在代码本身内工作,或者记录用户完成并开始输入的时间?
有解决方案吗

2 个答案:

答案 0 :(得分:2)

因为您在允许用户播放之前分配给resultend 。此外,第一个if-body中的start毫无意义。

答案 1 :(得分:0)

您将startend设置为一次,位于顶部。如果您想衡量游戏中的特定时刻,则需要在当时致电datetime.datetime.now() 。提及start不会那样做:

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)