Python:一天中的执行时间

标签 python

我写了一个小脚本来获取即时股票价格。

#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/

相关文章:

javascript - chrome 上的 contentType 错误

python - pyQT4 py3无法在QFrame背景中显示图像

Python Pandas : Group datetime column into hour and minute aggregations

python - 新手查询: mocking in python

python - 使用给定范围内的随机数初始化矩阵 - python

python - 在对数对数刻度上使用 matplotlib 拟合曲线

python - 列出所有无线网络 Python for PC

python - 为 tkinter 小部件创建一个类来调用默认属性

python - 从 Python 程序向命令行提示符发送输入

python - Micromamba 和 Dockerfile 错误 :/bin/bash: activate: No such file or directory