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

时间:2014-05-07 20:56:44

标签: python datetime python-3.x time python-3.2

我创建了一个程序,要求用户输入给定的TimeTypeSeconds/Minutes)和objectivetimeinteger)(例如,如果用户输入秒和然后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)

1 个答案:

答案 0 :(得分:2)

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.now()

的日期时间对象

要比较日期时间对象,您只需使用比较运算符即可。例如,

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

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

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