如何将输入的分/秒格式化为datetime.now()格式?



我创建了一个程序,要求用户输入给定的TimeType (Seconds/Minutes)和objectivetime (integer)(例如,如果用户输入秒,然后5,那么目标时间是5秒)。此外,程序还检查开始时的时间,然后检查之后的时间,以计算elapsed_time。然后我想检查elapsed_time是否大于或等于objective time。我写的代码如下所示(减去ab之间的其他无关代码)

import time, sys, os, random
a = datetime.datetime.now().replace(microsecond=0)
#random code...
b = datetime.datetime.now().replace(microsecond=0)
timetype = input("Enter time type: ")#Either Seconds or Minutes
objectivetime = input("Enter objective time: ")#This will be an integer
if timetype == 'Seconds':
    #convert objectivetime to seconds and present in same format as a or b
else:
    #convert objectivetime into minutes and present in same format as a or b
elapsed_time = b-a
if objectivetime<=elapsed_time:
    'Well done'
else:
    'You have exceeded the objective time'

是否有任何方法可以编辑代码,以获得客观时间以与ab (start_time和end_time)相同的方式格式化??

更新 --------------------------------------------------------------------------

我该如何确定哪个时间更大(elapsed_time或objtime)??

参见更新后的代码:

import time, sys, os, random
import datetime
a = datetime.datetime.now().replace(microsecond=0)
print(a)
#random code...
time.sleep(3)
b = datetime.datetime.now().replace(microsecond=0)
timetype = input("Enter time type: ")#Either Seconds or Minutes
objectivetime = input("Enter objective time: ")#This will be an integer
objectivetime = int(objectivetime) # I noticed you didn't do this in your code
delta = None
if timetype == 'Seconds':    
    delta = datetime.timedelta(seconds = objectivetime)
else:
    delta = datetime.timedelta(minutes = objectivetime)
objtime = a + delta
print(objtime)
#How would I work out which time is greater?? (elapsed_time or objtime)
elapsed_time = b-a
print(elapsed_time-objtime)
objectivetime = int(objectivetime) # I noticed you didn't do this in your code
delta = None
if timetype == 'Seconds':    
    delta = datetime.timedelta(seconds = objectivetime)
else:
    delta = datetime.timedelta(minutes = objectivetime)
objtime = a + delta

这将给你一个datetime对象,如datetime.now()

要比较datetime对象,只需使用比较操作符。例如,

b <= objtime # Finished before (or on) the objective time
b > objtime  # Finished after the objective time

你甚至不需要从b中减去a !如果您仍然需要,那么比较时间增量

elapsed_time <= delta # Finished before (or on) the objective time
elapsed_time > delta # Finished after the objective time

相关内容

  • 没有找到相关文章

最新更新