I have a very simple Python script in which I'm trying to print an updated timestamp (taken from a server by APIs) every n seconds.
After importing a custom module (FinexAPI) and the time module:
import FinexAPI
import time
and setting up the variable to get the server timestamp:
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
if I perform:
print when
I'm getting the timestamp up to date. If I perform it again, I can see a new updated timestamp. Untill now there's no problem at all.
Now let's suppose I need to perform an "updated timestamp print" every 5 seconds:
def getNewTimestamp():
print when
time.sleep(5)
while True:
getNewTimestamp()
But with this code I'm getting the same timestamp every 5 seconds. I suppose the problem is that I'm defining when outside the getNewTimestamp function, so it basically keeps printing the same non-updated timestamp. But even if I define it inside the function I still get no update on the timestamp.
Another thing I'm thinking about is that while loop is not the best choice in this scenario, but that would be another story (I think...). Can someone help me figuring out what am I doing wrong and what is the best way to obtain and print the updated timestamp every 5 seconds?
You have to call the API in the loop:
def getNewTimestamp():
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
print when
while True:
getNewTimestamp()
time.sleep(5)
Related
Alright,the problem is i'm trying to build a personal assistant with my amateur skills.
I want to display the time which should be running and not be static.
This is what you wanted ? create a endless loop (Since you didn't mention in what situation the loop will end, I assume it will run infinitely until you manually end it) and print() with end='\r' (replace prev print) and pause and refresh every second
import time
import datetime
while True:
now = datetime.datetime.now()
print(f"Current Date and Time: {now} ", end='\r')
time.sleep(1)
I am trying to use APScheduler to automate a function call. It is supposed to read a date from a website I scrape, and then at a certain time relative to that date call the function (2 minutes before). The code for this portion of the project is here:
for mtp, url, track in zip(mtp_num_final, url_list, race_list):
scheduled_time = datetime.now() + relativedelta(minutes =+ (mtp - 2))
print(scheduled_time.strftime('%m-%d-%Y %I:%M%p'))
scheduler.add_job(two_minute_scrape(url, track, 5), 'date', scheduled_time)
The basic gist of the above code is that race_list and and url_list hold data which the two_minute_scrape function needs. I get the amount of minutes + 2 that I want to wait from mtp num final. When I run this code, the printed out date is correct - it knows exactly when I want to run the code, but then it IMMEDIATELY runs two_minute_scrape instead of waiting for that time. Is there anyway to solve this?
Thanks!
So I want my discord bot to send out a message in the server every morning at 7 am. Using my variable time which is:
time = datetime.datetime.now()
and doing time.hour and time.minute, I can make it print something at the time i want using:
if time.hour == 7:
print('Its 7 am')
but using a whle statement datetime doesnt actually refresh the time. Second of all if there are any discord.py people how would i send the message without using an event refernec or command?
This should do what you want.
time = datetime.datetime.now
while True:
if time().hour == 7 and time().minute == 0:
print("Its 7 am")
sleep(60)
The reason the time doesn't actually refresh in your code is that you are storing the result of a function in the variable, not the function itself. If you don't include the parenthesis then the function gets stored in the variable so it can be called later using variable().
This question could already be answered on the following link:
Python - Start a Function at Given Time
Given the following information:
Reading the docs from http://docs.python.org/py3k/library/sched.html:
Going from that we need to work out a delay (in seconds)...
from datetime import datetime
now = datetime.now()
Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)
# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
You can then use delay to pass into a threading.Timer instance, eg:
threading.Timer(delay, self.update).start()
You could take a look at https://schedule.readthedocs.io/en/stable/
Install schedule with pip:
$ pip install schedule
You could do something like that:
import schedule
import time
def job():
print("Its 7 am")
schedule.every().day.at("07:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
I'm using Python 2.7 and want to use the datetime functions to calculate a user defined time to run a small pump. I know I'm missing something obvious but I've searched until I can't see straight. I have a textCtrl that the user will enter the minutes he wants the pump to run. Then a button click will start the scheduler and check to see if it's time to turn off the pump:
def timedPump(val):
now = datetime.datetime.now()
timeOff = now + datetime.timedelta(minutes=int(val))
if timeOff > now:
print 'pumpOn'
else:
print 'pumpOff'
return True
The problem is that datetime.datetime.now() updates everytime. How do I make it so that now = the time that the button was clicked?
This would be my solution to the problem:
from time import sleep
def pumpcheck(timer_in_minutes):
time_clicked = datetime.datetime.now()
now = time_clicked
timeDiff = datetime.timedelta(minutes=int(timer_in_minutes))
while (time_clicked + timeDiff > now):
print 'pumpOn'
now = datetime.datetime.now()
sleep(2)
print 'pumpOff'
It saves the time when the button was pushed and then checks in a loop, if the time is rfeached, if not, it update the current time, says pump is still on and sleep for a little while to not bloack cpu recources. When the time is reached, it says pumpoff
There is some information missing as to how timedPump is evaluated. I guess it's a simple loop.
What needs to happen is there have to be two functions, one that sets a turnOff-time and one that evaluates weather to turn on / off the pump.
This can be implemented as two methods of a class:
class PumpControl(object):
def setTime(self, val):
now = datetime.now()
self.timeOff=now + timedelta(minutes=int(val))
print 'pumpOn'
def checkTime(self):
if self.timeOff < datetime.now():
print 'pumpOff'
This way you would create a PumpControl object and then repeat checkTime:
controller = PumpControl()
#inside your loop
controller.checkTime()
#when you want to set the time
controller.setTime(val)
This should work across threads as well, so you can have one thread repeating and another asking for the time.
This sounds like something outside the scope of a single function. Either split the logic into two functions, or use a class to preserve start_time
Trying to set a cron job on my Skygear python cloud code, but not sure what I should enter in the decorator. I only know that it will work for units in second, but how to schedule a job to run every 12 hours? It is hard to calculate the seconds every time.
My code is like this, the function is to call a POST request:
#skygear.every('#every 43200s')
def post_req():
print ('scheduled to run every 12 hours')
url = myurl
ref = something
r = requests.post(myurl, data = {'token':some_token, 'ref':something})
It actually works but is there some ways to write in a better format?
It seems like skygear.every also accepts crontab notation… so 0 */12 * * * could also do the trick.
Edit: Reading the robfig/cron docs, the best solution would actually be just #every 12h