Python 2.7 .datetime.datetimenow() and datetime.timedelta() - python

I have this following code and am stuck in the while loop
I know there is a problem with the while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)): line.
Can anyone help please ?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)

You are asking if the current time is smaller than the current time plus a delta. Of course that's going to be true each and every time, the future is always further away into the future.
Record a starting time once:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
If wait_time doesn't vary in the loop, store the end time (current time plus delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
It may be easier to just use time.time() here:
end = time.time() + 60 * wait_time
while time.time() < end:

You use datetime.datetime.now() in your while loop, what means each iteration you check if the time now is lower then the time now + delta.
That logically wrong, because it will be True forever as the time now will be always lower than the time now plus delta.
You should change it to this:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"

Related

My 'if int(time.time()) % 2 == 0:' doesn't always print out even sec

start = int(time.time())
while True:
if int(time.time()) % 2 == 0:
img = ImageGrab.grab()
saveas = 'screenshot' + str(int(time.time())) + '.png'
img.save(saveas)
elif start + 30 == int(time.time()):
break
result : https://i.stack.imgur.com/Aqdv6.png
Hi guys. It's a simple code but not working accurately.
I wanted to save a screenshot of my screen for every 2 seconds.
but in the result, I have some of those odd second files like 'screenshot1552893309.png'. What should I do to fix it?
This happens because "time flies."
You are calling time.time() at most three times per iteration of the while loop.
Each call of time.time() returns the UNIX time at the given call. In your code, each call can be invoked at different seconds (thus returning different timestamps.)
For example, consider this situation: time.time() from if int(time.time()) % 2 == 0: returns 1552893308.0, so the condition is satisfied, but the next call returns 1552893309.0, which will leave its trace to the file name.
Instead, you might want to call time.time() only once per iteration, and then do what you want with that timestamp.
start = int(time.time())
while True:
current_time = int(time.time())
if current_time % 2 == 0:
img = ImageGrab.grab()
saveas = 'screenshot' + str(current_time) + '.png'
# or you can also say
# saveas = f'screenshot{current_time}.png'
img.save(saveas)
elif start + 30 <= current_time:
break
Note the change of the boolean operator in elif. start + 30 == current_time seems too vulnerable to making a infinite loop.
Also note the commented use of f-strings, which was introduced in Python 3.6
while True:
# save time into variable:
start = int(time.time())
if start % 2 == 0:
img = ImageGrab.grab()
# use start time for file name:
saveas = 'screenshot' + str(start) + '.png'
img.save(saveas)
...
The time, where you check it for even and the time where you are using it to save image would be different since they are in different statement. You can save the current time in every iteration, and use the saved time in image files name if its even.
Sample code :
while True:
t = int(time.time())
if t % 2 == 0:
img = ImageGrab.grab()
saveas = 'screenshot' + str(t) + '.png'
img.save(saveas)

comparing three variables on if statement

I need some help with get pass on the if statement. I have a problem with if statement as I am trying to get pass when I am trying to compare on the values using three variables.
start_time = '22:35'
current_time = '23:48'
stop_time = '00:00'
if current_time == start_time:
print "the program has started"
elif start_time != current_time < stop_time:
print "program is half way"
elif current_time > stop_time:
print "program has finished"
I can get pass on each if statement with no problem, but my problem is when I have the variable start_time with the value 22:35 which it is not equal to current_time value 23:48. So how I can compare with the values between the start_time and current_time as I want to compare to see if it is less than the value 00:00 from the variable stop_time?
I want to check if the value from the variable stop_time which is less than the current_time and start_time.
Just imagine you are watching the tv program which it start at 22:35 in your current time. You are watching which it is less than before the program finish at 00:00, so you check the time again later before the finish time 00:00, it say it is still half way through. Then you check it later at your current time which it is after than 00:00 so it say the program has finished.
Well on my code, I will always get pass on the elif current_time > stop_time: as i always keep getting the print "program has finished" which I should have print "program is half way" instead.
How can you compare three values between the variables start_time and current_time to see if it is less than and check to see if it is less the value 00:00 from the variable stop_time?
EDIT: Here is what I use them as a string when i am getting the hours and minutes from the date format especially year, month, day, hours, minutes and seconds
start_date = str(stop_date[0]) #get start_date date format from database
stop_date = str(stop_date[1]) #get start_date date format from database
get_current_time = datetime.datetime.now().strftime('%H:%M')
get_start_time = time.strptime(start_date, '%Y%m%d%H%M%S')
start_time = time.strftime('%H:%M', get_start_time)
get_stop_time = time.strptime(stop_date, '%Y%m%d%H%M%S')
stop_time = time.strftime('%H:%M', get_stop_time)
current_time = str(get_current_time)
Using two comparisons and the and logical we could create something like this:
if current_time > start_time and current_time < stop_time:
#do work
But that actual problem is dealing with date and time
current_time = datetime.now() #lets say this is 2016, 2, 12, 17:30
start_time = datetime.datetime(2016,2,12,16,30) # or datetime.strptime(start_time)
end_time = datetime.datetime(2016,2,13,0,0)
if current_time == start_time:
print "the program has started"
elif current_time > start_time and current_time < stop_time:
print "Program is still running"
elif current_time > stop_time:
print "program has finished"

Stopping Stopwatches

I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():

printing out letter every min Python

so i am trying to figure this out for school. Im trying to print x out every minute and every ten min it will print on a new line. so far i cant get the "printing x" every min down. can someone please help.
this is my code
import time;
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
print (time.time())
def tenMin(oldTime):
newTime = time.time()
if ((newTime - oldTime)>= 25):
return True
else:
False
while (True):
if (tenMin==True):
print ("x")
newTime = time.time()
oldtime = time.time()
else:
oldTime = time.time()
continue
Your first problem is in the line
if (tenMin==True):
You compare a function reference to a boolean, clearly the answer would be False. You have to pass a parameter
if (tenMIn(oldTime)):
...
First you have some issues with you code:
else:
False - This is not true syntax in python.
If you want timer, why are you asking the user for input?
You have a logic problem:
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
time.time is float yes, but can a user really know what to print in UnixTime?
I'll suggest a simple solution it's not the very best but it works.
It will print "x" every 1 Min and after 10 Min it will print "\n" (new line)
import time
def main():
#both timers are at the same start point
startTimerTen = time.time()
startTimerMin = startTimerTen
while True:
getCurrentTime = time.time()
if getCurrentTime - startTimerTen >= 600:
# restart both parameters
startTimerTen = getCurrentTime
startTimerMin = getCurrentTime
print "This in 10 min!\n"
if getCurrentTime - startTimerMin >= 60:
# restart only min parameter
startTimerMin = getCurrentTime
print "x"
#end of main
if __name__ == "__main__":
main()

Creating a timer in python

import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box, The dialog box is not the problem. But my minutes variable does not increment in this code.
See Timer Objects from threading.
How about
from threading import Timer
def timeout():
print("Game over")
# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()
# wait for time completion
t.join()
Should you want pass arguments to the timeout function, you can give them in the timer constructor:
def timeout(foo, bar=None):
print('The arguments were: foo: {}, bar: {}'.format(foo, bar))
t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
You can really simplify this whole program by using time.sleep:
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# Loop until we reach 20 minutes running
while mins != 20:
print(">>>>>>>>>>>>>>>>>>>>> {}".format(mins))
# Sleep for a minute
time.sleep(60)
# Increment the minute total
mins += 1
# Bring up the dialog box here
I'd use a timedelta object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
or
minutes = minutes + 1 #instead of mins = minutes + 1
but here's another solution to this problem:
def wait(time_in_seconds):
time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.
All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.
import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()
# this is kind of timer, stop after the input minute run out.
import time
min=int(input('>>'))
while min>0:
print min
time.sleep(60) # every minute
min-=1 # take one minute
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that
minutes = 0
and then
mins = minutes + 1
it is the same as saying
mins = 0 + 1
I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".
What you have to do first is place your
minutes = 0
declaration outside of your while loop. After that you can delete the
mins = minutes + 1
line because you don't really need another variable in this case, just replace it with
minutes = minutes + 1
That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.
I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.
from datetime import datetime
now=datetime.now()
Sec=-1
sec=now.strftime("%S")
SEC=0
while True:
SEC=int(SEC)
sec=int(sec)
now=datetime.now()
sec=now.strftime("%S")
if SEC<sec:
Sec+=1
SEC=sec
print(Sec) #the timer is Sec

Categories