How can I set time in this Python code? [duplicate] - python

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 4 years ago.
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
def handle_data(context,data):
security = g.security
order(security, 100)
I want operation this code at 10:00 o'clock, how can write the code?

You can use the sched module or simply loop through datetime, although as AChampion points out, on a *nix platform, it's easier to use cron.
This stackoverflow question does into more detail about sched and datetime.
Essentially:
from datetime import datetime as dt
while True:
if dt.now().hour == 10: # for 10 o'clock
initialize(context)
handle_data(context,data)
time.sleep(60) # Minimum interval between task executions
else:
time.sleep(10) # The else clause is not necessary but would prevent the program to keep the CPU busy.

Related

How would I be able to have certain lines of code be executed randomly? [duplicate]

This question already has answers here:
Percentage chance to make action
(4 answers)
Closed 10 months ago.
I feel this should be an obvious answer, however, I am having issues coding a personal project of mine. How would I be able to have certain lines of code be executed randomly?
Not from the project itself but the principles are still, say for example I would want the following code to be executed every 1/1000 times or so.
print("Lucky!")
How would I exactly be able to do that?
Set a trace function that will have a 1/1000 chance to print:
import random, sys
def trace(frame, event, arg):
if random.random() < 1/1000:
print("Lucky!")
return trace
sys.settrace(trace)
You're welcome to test it with a 1/2 chance.
Generate a random integer in the range [0,1000). Pick any single value in the range, and check for equality to see if you should print.
import random
def lucky():
if random.randrange(1000) == 42:
print("Lucky!")

python delay a program for n seconds [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 3 years ago.
is there a function in python that delays a program from running for n number of seconds?
I am trying to achieve something like this:
print("Hello")
delay(5) #delays the program by 5 seconds
print("World!")
Any help will be greatly appreciated, Thank you!
Sure!
import time
print("Hello")
time.sleep(5) #delays the program by 5 seconds
print("World!")

function start to run in the first second of the minute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want a function start to run in the first second of the minute but i can't do it
this is my code
import datetime
now = datetime.datetime.now()
while not (now.second == "01"):now = datetime.datetime.now()
Your code doesn't work because you're comparing a number (now.second) to a string "01". In Python numbers and their string representations are not equal (unlike some other programming languages), so this will never work.
Try comparing with 1 (or maybe 0 if you really want the top of the minute). And maybe instead of busy-looping (which will use all of one core of your CPU while waiting), you should perhaps instead use time.sleep to wait until the start of the next minute.
import datetime
import time
now = datetime.datetime.now()
sec = now.second
if sec != 0:
time.sleep(60-sec)
# it should be (close to) the top of the minute here!
There's always some unpredictability when dealing with time on a computer, since your program might be delayed from running by the OS at any moment (more likely if your CPU is very busy). I'd not worry about it too much though, likely it's good enough to be very close to the right time.
import time
while True:
if time.strftime("%S") == "01":
#Run Your Code
time.sleep(59)
That would pound your system like crazy, give it a little room to breathe:
import time
while True:
current_seconds = time.gmtime().tm_sec
if current_seconds == 1:
print("The first second of a minute...")
time.sleep(0.9) # wait at least 900ms before checking again
You can further streamline it by calculating how much time to wait before you start checking again - if you're interested only in the first second you can safely sleep until the end of the minute.

Higher precision logging module time format? [duplicate]

This question already has answers here:
Python Logging Module logging timestamp to include microsecond
(7 answers)
Closed 5 years ago.
I am using the logging module from Python and I need to get information about the starting and ending time of different functions calls. For this, I am currently using
formatter = logging.Formatter('%(message)s %(asctime)s.%(msecs)03d %(levelname)s',
datefmt='%H:%M:%S')
Since the calls of a particular function do not last more than a few milliseconds, I would like to get a better precision and have more decimal digits. How can I do this?
I nice solution at: Python logging: use milliseconds in time format
For showing milliseconds:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
An extensive example so you can compare:
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
Check this answer and also this doc to see all the milliseconds you can use:
import time
current_milli_time = lambda: int(round(time.time() * 1000))
Remember, 1000 milliseconds = 1 second, so you will be able to see 3 digits of milliseconds after the last second

Pausing a while loop [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 8 years ago.
I have a query for a small program that I am running. I was wondering if there was any way to pause a while loop in python for an amount of time? Say for example if I wanted it to print something out, then pause for say (1) second, then print it out again?
There is not really a point to this program I am more doing it for something to do while bored.
I have checked other questions and none seemed to really answer what I was asking.
import time
while ...
print your line
time.sleep(1) # sleep for one second
time sleep method
Yes. There is a function called sleep that does exactly what you want:
while true:
print "Hello!\n"
time.sleep(1)

Categories