重新格式化输出Python

时间:2019-05-07 15:41:09

标签: python python-3.x interactive-brokers

当前,我正在尝试从IB API请求数据,但是存在一个小的格式化问题。

API给我以下输出:

AAPL; 20190507 16:20:00; price; price; price; price; number

我希望数据返回为:

AAPL; 20190507; 16:20:00; price; price; price; price; number

我正在使用以下代码

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("error: ", reqId, " ", errorCode, " ", errorString)

    def historicalData(self, reqId, bar):
        print("AAPL", ";", bar.date, ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)

def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    contract = Contract ()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqHistoricalData(0, contract, "", "1 D", "1 min", "TRADES", 0, 1, False, [])

    app.run()

if __name__ == "__main__":
    main()

bar.date在这种情况下为我提供了日期和时间

print("AAPL", ";", bar.date, ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

尝试一下:

'; '.join(bar.date.split(' '))

或者:

bar.date.replace(' ', '; ')

这两种方法都将用分号和空格替换日期/时间输出中的空格。

答案 1 :(得分:0)

据我了解,bar.date包含"20190507 16:20:00"

因此,您可以在提供的最后bar.date中将"; ".join(bar.date.split(" "))替换为print()