Can't get code to execute at certain time - python

I am trying to get some code to execute at a certain time but I can't figure out what the problem is here. Please help?
import datetime
dt=datetime
set_time=dt.time(12,53)
timenow=dt.datetime.now()
time=False
while not time:
if timenow==set_time:
print("yeeehaaa")
time=True
break
else:
print("naaaaa")

First of all you have to update the time inside the loop or it will always be comparing the same timenow to set_time, then convert all to just an hour/minute string and compare
import datetime
dt=datetime
set_time=str(dt.time(14,19))[0:5]
timenow=dt.datetime.now().time()
time=False
while not time:
timenow=str(dt.datetime.now().time())[0:5]
# print(timenow)
if timenow==set_time:
print("yeeehaaa")
time=True
break
else:
print("naaaaa")

Changing your code to something like this should solve your issue:
import datetime.datetime as dt
set_time=dt.time(12,53)
# the loop waits for the time condition to be met.
# we use the lower than condition in order not to miss the time
# by a few fraction of second.
while (dt.now() < set_time):
time.sleep(0.1) # 100ms delay
# reaching there implies the time condition is met!
print("it is time!")
However there is a much simpler alternative which would consists in get the time delta between the current time and the target time in order to make one single wait with time.sleep(time_delta_s).

Related

Function that substracts a certain number every second on Python

I have been wondering if there is a way to create a function that subtracts one number from another but only at a given amount of time. I have read the time library, but I am still trying to figure it out. For example:
def TimeFunction:
t = 60
#What should I need to put here so for every second that passes, it subtracts 1?
This is what you are literally asking for:
import time
def TimeFunction():
t = 60
while True:
time.sleep(1)
t -= 1
Although this is not very satisfying, because your program blocks on sleep() and nothing else would be able to see the value of t.
Do you want to modify your question now and ask for something slightly different?

how to terminate python script using while loop and get the result?

i would like to generate random numbers for 5 minutes. after that, i would like to know the most common numbers.
my question is:
I am not sure about how much time I need. Can i MANUALLY terminate the script at 1 minute or 1 minute 19 seconds and get the result
my code is as follows:
import random
from collections import Counter
t_end = time.time() + 60*5
numbers = []
while time.time() < t_end:
number=''.join(map(str, [random.randint(0,9)for value in range(0,4)]))
numbers.append(number)
print(Counter(numbers))
There are a myriad number of options:
print an intermediate result every 5s or so and abort the script with ctrl+C
check if space or something else is pressed, if so, abort the loop (see here for how to)
listen to signals and handle accordingly (this could also gracefully terminate the script for option 1)
open a socket and listen to a socket if a stop signal comes in
create a gui with TKinter or what and add a stop button
...
The first one is the easiest but also the most quick&dirty one. For the second option, the following script should get you started (your script was working for me after adding whitespaces and linebreaks):
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
Assuming python3 and windows: Note that keyboard is not shipped with python on default. You need to install it with pip3 install keyboard. Pip3.exe might not be on your path. cd to where you installed python and look around. For me it was in the Scripts-folder (my installation is pretty messed up though).
import random
from collections import Counter
import time
t_end = time.time() + 60*5
numbers = []
while time.time() < t_end:
number=''.join(map(str, [random.randint(0,9)for value in range(0,4)]))
numbers.append(number)
if time.time()==(t_end-60*4): # break a 1 min
break
print(Counter(numbers))
As luigigi already mentioned in the comment, you could simply use the number of iterations as a limit, and use a for-loop:
number_of_iterations = 10000
for i in range(number_of_iterations):
place_your_function_here()
However, if you for some reason really want to use the time, here is how you can do it: Update the current time at the bottom of your while block, and in the continuing condition of the while loop, compare it to the finish time:
import datetime
delta_in_seconds = 60
finish = datetime.datetime.now() + datetime.timedelta(0, delta_in_seconds)
while time < finish:
place_your_function_here()
time = datetime.datetime.now()

How can you update local time from the datetime module?

I am writing a program that uses a while loop to check if it is a certain time, and if it is that certain time, it prints a statement. I have all the if-statements set up, but the time does not update once the program starts (if I start the program at 6 pm, it will always output 6 pm for local time). Is there a way to update the time within the while loop?
I tried to research some additional functions/methods to datetime, but from what I have seen, I have not been able to find any that updates the time while the program is running. Additionally, forums regarding datetime and locale time that I have found on stackoverflow are commonly ones that just explain how to obtain the locale time once (ex, Python datetime module current time in HR:MIN:SEC). Other forums regarding locale times that I have found also tended to be in different languages, particularly C# and PHP. Please correct me if there is another forum that answers my question!
from datetime import date
from datetime import time
from datetime import datetime
import time
import webbrowser
now = datetime.now()
sleep = False
today = date.today()
roundCheck = 0
print("Awaiting time check...")
while sleep != True:
print('Up here...')
if roundCheck != 0:
print('Stuck in time...')
time.sleep(60)
print('Time is done')
if str(now.strftime('%H')) == '20' and str(now.strftime('%M')) == '05':
print('Now the while loop will end')
sleep = True
roundCheck = 1
print('Another round has passed')
print('Outside while loop')
When the time is 20:05, sleep should be set to true and the print statement outside the while loop can be executed. However, when I start the program at an earlier time (20:00, for example), it only uses that time for checking now.strftime().
now never changes. You simply need to put now = datetime.now() in the while loop.

How to print something at a specific time of the day

Is it possible to have python 2.7 print something at a specific time of the day. For example if I ran the program at 15:06 and coded it to print "Do task now" at 15:07 it prints it. So no matter what time you ran the program once it hit 15:07 it would print "Do task now." In addition is it possible to have it print every week at this time?
I would suggest installing the library schedule, if you're able to.
Use pip install schedule
Your code would look like this if utilizing schedule:
import schedule
import time
def task():
print("Do task now")
schedule.every().day.at("15:07").do(task)
while True:
schedule.run_pending()
time.sleep(1)
You can adjust time.sleep(1) as necessary to sleep for longer if a 1s interval is too long. Here is the schedule library page.
If you're not using cron, then the general solution is to find the time remaining until you need the event to occur, have the program sleep for that duration, then continue execution.
The tricky part is to have the program find the next occurrence of a given time. There are some modules for this, but you could also do it with plain code for a well-defined case where it is only a fixed time of day.
import time
target_time = '15:07:00'
current_epoch = time.time()
# get string of full time and split it
time_parts = time.ctime().split(' ')
# replace the time component to your target
time_parts[3] = target_time
# convert to epoch
future_time = time.mktime(time.strptime(' '.join(time_parts)))
# if not in the future, add a day to make it tomorrow
diff = future_time - current_epoch
if diff < 0:
diff += 86400
time.sleep(diff)
print 'Done waiting, lets get to work'
While python is not ideal to schedule something; there are better tools out there. Yet, if this is desired to be done in python below is a way to implement it:
Prints at scheduled_time of 11AM:
import datetime as dt
scheduled_time = dt.time(11,00,00,0)
while 1==1:
if (scheduled_time < dt.datetime.now().time() and
scheduled_time > (dt.datetime.now()- dt.timedelta(seconds=59)).time() ):
print "Now is the time to print"
break
There are two if conditions with an intent to print within one minute; a shorter duration can be chosen. But the break immediately after print ensures that print is executed only once.
You would need to extrapolate this so that code is run across days.
Refer: datetime Documentation

Running Python at a Certain Time with Datetime

I would like to execute a portion of a script at 8 am each day. I have created a simplified test case that has no syntax error, but does not work properly. I think it may be because my if statement is using the time as a string, but it won't compile any other way. What am I doing wrong?
import datetime
while True:
if datetime.datetime.now().time() == "19:00:00.000000":
print "it's time!"
If you are on a system with cron, then it would be better to set up a cron job. However, your problem is fixable from within Python:
First, as you noted, datetime.datetime.now().time() returns a datetime.time object, not a string:
In [89]: datetime.datetime.now().time()
Out[89]: datetime.time(19, 36, 13, 388625)
Also, although datetime.datetime.now().time() == datetime.time(19, 0) would be
valid Python, the chance that you happen to execute time() at just the right
moment is very slim since datetime.datetime.now() has microsecond
resolution. So it would be better to test if the current time falls within some
range.
However, since you only want to run the function once per day, you could instead measure the total number of seconds between now and when you want to run the function and sleep that number of seconds:
import datetime as DT
import time
while True:
now = DT.datetime.now()
target = DT.datetime.combine(DT.date.today(), DT.time(hour=8))
if target < now:
target += DT.timedelta(days=1)
time.sleep((target-now).total_seconds())
# do something
If you want to keep your code simple, you can use the below code:
import datetime
import time
while True:
time.sleep(1)
if datetime.datetime.now().time().strftime("%H:%M:%S") == '19:00:00':
print ("it's time!")
Sleep is used to generate only 1 row per 1 second (without this you will print thousands of lines. Also it is worth to convert time to string.

Categories