Question

I have created a program which requires the user to input a given TimeType (Seconds/Minutes) and an objectivetime (integer) (e.g. if the user inputs Seconds and then 5, then the objective time is 5 Secs). In addition, the program also checks the time at the start and then checks the time after to work out the elapsed_time. I then wanted to check if the elapsed_time is more than or equal to the objective time. The code i have written is shown below (minus the other irrelevant code in between a and b)

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'

Is there any way that the code could be edited to get the objective time to be formatted in the same way as a and b (start_time and end_time)??

Update--------------------------------------------------------------------------

How would I work out which time is bigger (elapsed_time or objtime)??

See updated code:

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)
Was it helpful?

Solution

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

This will give you a datetime object like datetime.now()

To compare the datetime object, you can simply use the comparison operators. For example,

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

You don't even need to subtract a from b! If you still want to, then compare the time deltas instead

elapsed_time <= delta # Finished before (or on) the objective time
elapsed_time > delta # Finished after the objective time
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top