Program idle while comparing two dates in while statement - python

Don't know how to properly describe my problem, but when I compare two datetime objects in while statement the whole program stops working.
I have a method work()
import time
import datetime
def work():
now = None
intr = 10.0
d = datetime.datetime.utcnow()
least_time = datetime.datetime.combine(datetime.datetime.today(), datetime.time(10, 10, 00))
finish = datetime.datetime.combine(datetime.datetime.today(), datetime.time(10, 10, 20))
if datetime.datetime.today().weekday() == 0:
least_time = datetime.datetime.combine(datetime.datetime.today(), datetime.time(11,10,00))
finish = datetime.datetime.combine(datetime.datetime.today(), datetime.time(11,10,20))
while d <= finish:
d = datetime.datetime.utcnow()
if intr > 1 and d >= least_time:
intr = 1
print("Interval set to 1 sec")
if now == None:
now = time.time()
if time.time() - now >= intr:
print("Work")
print("_____")
now = None
print("End")
And, if I call print() or something else before that method:
print("1")
print("2")
print("3")
work()
The program just idle and do nothing.

What happens depends on your current time zone.
The call to datetime.datetime.utcnow() gives a datetime in UTC,
whereas datetime.datetime.today() gives you current datetime for your time zone (which you machine has):
Changing:
d = datetime.datetime.utcnow()
to:
d = datetime.datetime.now()
or to:
d = datetime.datetime.today()
would fix your problem.

Related

How to Execute a Function after A particular time Like Click a button at 10 am or 11 am?

I tried these codes.
x = 6
while 1:
if x < 0.999:
break
#execute you function after 6 seconds.
x -= 0.01
sleep(0.01)
But i need to execute on a particular time . So i tried this:
if (self.is_hour_between("09:55:00", "11:20:00")) == True:
#your function
else:
#your function
def time_between(self, start, end):
# Time Now
now = datetime.now().time()
# Format the datetime string
time_format = "%H:%M:%S"
# Convert the start and end datetime to just time
start = datetime.strptime(start, time_format).time()
end = datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
i wanted to run the function at exactly 10 Am and 11Am .If its not the time then wait for it.else if its the time then go for it without waiting
Anwser :
import datetime
import time
while True:
current_dt = datetime.datetime.now()
time_a = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 9, 55)
time_b = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 11, 20)
if (time_a<current_dt) and (time_b > current_dt):
print('ok')
else:
time.sleep(60)

"How to print list data on a specific time delay list ?"

I want to print list data on the specific delays which are on another list. I Want to loop this process for a specific time, but I'm unable to implement it in a thread.
from time import sleep
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
# print(f"{data} delay {delay} & time is {t} ")
# sleep(delay)
i = 0
while i < len(list1):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
sleep(list2[i])
i += 1
else:
print("All Data is printed")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
Expected output: On first, loop it should print all list data but in the second loop, it should run as per the delay.
1st time: Hello, Hi, Ola
after that
1. Every 5 seconds it should print Hello
2. Every 10 seconds it should print Hi
3. Every 7seconds it should print Ola
Actual Output: List of data is getting printed as per the delay.
Hello delay 5 & time is 11:41:45
Hi delay 10 & time is 11:41:50
Ola delay 3 & time is 11:42:00
All Data is printed
Hello delay 5 & time is 11:42:03
Hi delay 10 & time is 11:42:08
Ola delay 3 & time is 11:42:18
You can try comparing the current time with the start time, for example:
time.sleep(1);
diff = int(time.time() - start_time)
if (diff % wait_time == 0):
print(text_to_print)
Here is the full code implementing this:
from time import sleep
import time
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
starttime=time.time()
diff = 0
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
for i in range(len(list1)):
if (diff % list2[i] == 0):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
time.sleep(1);
diff = int(time.time() - starttime)
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
In accordance with your desired output, I believe threads are the best option, which means:
from time import sleep
import datetime
import threading
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
def __init__(self):
self.run = True
print ("1st time: Hello, Hi, Ola")
print ("Now: " + datetime.datetime.now().strftime('%H:%M:%S'))
def test(self, i):
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
while self.run:
sleep(list2[i])
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t}")
def stop(self):
self.run = False
if __name__ == '__main__':
obj = sampleTest()
t1 = threading.Thread(target=obj.test,args=(0,))
t2 = threading.Thread(target=obj.test,args=(1,))
t3 = threading.Thread(target=obj.test,args=(2,))
t1.start()
t2.start()
t3.start()
while Str_time < End_Time:
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
obj.stop()
t1.join()
t2.join()
t3.join()
print("All data is printed")
print("Time Is done")

How to set time limit using python

I am trying to create a little game with python. I already set everything but I would like to set a time limit. I found something on the internet but it is not working with this project but it works with another project.
c.create_text(450, 20, text = 'Time', fill = 'red')
c.create_text(650, 20, text = 'Score', fill = 'red')
time_text = c.create_text(450, 20, text = 'Time', fill = 'red')
score_text = c.create_text(650, 20, text = 'Score', fill = 'red')
def print_score(score) :
c.itemconfig(score_text, text = str(score))
def print_time(time) :
c.itemconfig(time_text, text = str(time))
ENNEMY_CHANCE = 10
TIME_LIMIT = 30
SCORE_BONUS = 1000
score = 0
bonus = 0
end = time() + TIME_LIMIT
#Main
while True :
if randint(1, ENNEMY_CHANCE) == 1:
create_ennemy()
move_ennemies()
hide_ennemies()
score += ennemy_kill()
if(int(score/SCORE_BONUS)) > bonus:
bonus += 1
end += TIME_LIMIT
print_score(score)
print_time(int(end - time()))
window.update()
But I get this:
end = time() + TIME_LIMIT
TypeError: 'int' object is not callable
If you know an easier way to set a time limit that would be super.
Did you import time? I think you used the "time" name as an integer variable somewhere in your code and you have ambiguous code. Try this to get current time:
import time as time_module
now = time_module.time()
Try this
import time
start = time.time() #the variable that holds the starting time
elapsed = 0 #the variable that holds the number of seconds elapsed.
while elapsed < 30: #while less than 30 seconds have elapsed
elapsed = time.time() - start #update the time elapsed

Wait until specific time

I'm writing a program that will do something if now == specific time and day and wait till that time if is not equal.
I have a morning, evening, days values, which shows start time, end time and today's day. I would like to make a program that check if today is a weekday and specific time (between morning and evening) if True to do something and if even one of these is False, gonna wait till that time and after that do something.
I did it with while loop but when it starts with False value(not in right time) it continue printing False even if that time came and value should change to True but it shows True when I start it in right time.
Here is the code:
import datetime
from datetime import date
from time import sleep
#setting values
now = datetime.datetime.now()
morning = now.replace(hour=9, minute=00, second=0, microsecond=0)
evening = now.replace(hour=16, minute=0, second=0, microsecond=0)
days = now.strftime("%A")
#check if time is in range and return True or False
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#check if today is weekday
if date.today().weekday() == 0:
dayz = True
else:
dayz = False
# If today weekday and time range do something
if dayz == True and timerange == True:
print("Yes")
while dayz == False or timerange == False:
sleep(5)
timerange = time_in_range(morning, evening, now)
print(timerange) #this printing false even if is right time.
# But it shows True when I turn it on in right time
You only initialize your now variable once and never update its value to the current now. You should update the value inside the while loop, for example:
while dayz == False or timerange == False:
sleep(5)
now = datetime.datetime.now()
...
If you are interested in checking just the hours to determine morning and evening as I can see in your code, you can use below snippet:
from datetime import datetime
from datetime import timedelta
from time import sleep
morning_hour = 9
evening_hour = 16
while True:
curr_time = datetime.now()
print("Current time : {0}".format(curr_time))
if curr_time.hour < morning_hour or curr_time.hour > evening_hour or not curr_time.isoweekday():
print("Job start conditions not met. Determining sleep time")
add_days = 0
current_day = curr_time.weekday() == 4
# Add 3 days for fridays to skip Sat/Sun
if current_day == 4:
add_days = 3
# Add 2 days for Saturdays to skip Sunday
elif current_day == 5:
add_days = 2
else:
add_days = 1
next_window = (curr_time + timedelta(days=add_days)).replace(hour=9, minute=0,second=0,microsecond=0)
delta = next_window - datetime.now()
print("Sleep secs : {0}".format(delta.seconds))
sleep(delta.seconds)
else:
print("Do something")
break

How to change speed at which text is printed (python)

What I am trying to accomplish is first text appears after 1 second. then 2, ect. till 10. then when time equals 10, the time decreases, so the text appears after 9 seconds, then 8 etc.
How could I fix this code so that it works properly?
The error:
Traceback (most recent call last):
File "C:/Users/Eric/Dropbox/time.py", line 13, in <module>
time.sleep(time)
AttributeError: 'int' object has no attribute 'sleep'
The code :
import time
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >=10:
time = t - 1
elif time <= 0:
time = t + 1
time.sleep(time)
Edit:
import time
x = 1
t = 1
time1 = 0
while x == 1:
if time1 == 10:
time1 = time1 - 1
elif time1 == 0:
time1 = time1 + 1
else :
time1 = time1 + 1
print time1
time.sleep(time1)
So I changed the program around abit, so I almost works correctly. What it does is count to 10, then 9 then back to 10.
ex. 1,2,3,4,5,6,7,8,9,10,9,10,9,10
how can I set it so that the program increases time to ten then decreases to zero then increases again?
You're overriding the imported time module (line 1) by your own time variable (line 4). You can:
rename your time variable to something else
import time
x = 1
t = 1
time_passed = t + 1 # use "time_passed" instead of "time" for example
while x == 1:
print time_passed
if time_passed >= 10:
time_passed = t - 1
elif time_passed <= 0:
time_passed = t + 1
time.sleep(time_passed)
alias the imported time module with import time as tm the use tm.sleep(time)
import time as tm # alias the time module as "tm" for example
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
tm.sleep(time) # use "tm" to refer to the module
only import sleep from time with from time import sleep and use sleep(time) instead
from time import sleep # only import "sleep" from time, not the whole module
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
sleep(time) # use "sleep" directly
After fixing this, you also need to somehow remember that you need to either increase or decrease the time at the next iteration. For example:
from time import sleep
x = 1
t = 1
time = t + 1
incr = True
while x == 1:
print time
if time >= 10:
time = 9
incr = False
elif time <= 0:
time = t + 1
incr = True
else:
if incr:
time = time + 1
else:
time = time - 1
sleep(time)
You're redefining 'time' after you import it...
Try using a different variable name.
Your time variable is conflicting with the module (time) that you imported. You could use curTime or myTime instead as your variable name.

Categories