我写了一个小脚本来获取即时股票价格。
#script to get stock data
from __future__ import print_function
import urllib
import lxml.html
from datetime import datetime
import sys
import time
stocks=["stock1","stock2","stock3","stock4","stock5"]
while True:
f=open('./out.txt', 'a+')
for x in stock:
url = "http://someurltofetchdata/"+x
code = urllib.urlopen(url).read()
html = lxml.html.fromstring(code)
result = html.xpath('//td[@class="LastValue"][position() = 1]')
result = [el.text_content() for el in result]
f.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' ' + x + ' ' + result[0])
f.write("\n")
f.close()
我希望该代码仅在股市开盘时间(即交易时间)获取数据。 (09:00 至 12:30 和 13:30 至 17:30)。
您能否建议一种在代码上隐式执行调度的方法? (不在操作系统级别)
最佳答案
如果您不能使用 cron(这是完成任务的最简单方法),您可以将其添加到您的代码中。如果在给定的时间范围内,它将下载数据,休眠 60 秒,然后再次运行。
while True:
now = datetime.now().strftime('%H%M')
if '0900' <= now <= '1230' or '1330' <= now <= '1730':
# your code starting with f=open('./out.txt', 'a+')
time.sleep(60)
关于Python:一天中的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138858/