pythoninteractive-brokers

how to convert integer from Interactive Brokers Clent Portal API to python datetime


I am using the Interactive Brokers Client Portal API to get historical data by using the package easyIB. I can't seem to find out in the documentation on how to convert the 13 digit timestamp to python's datetime.

The sample code to retrieve the data is here

   import easyib

   ib = easyib.REST() # default parameters: url="https://localhost:5000", ssl=False

   bars1 = ib.get_bars("AAPL", period="10w", bar="1d")
   print(bars1)

The output is for the part of the dataframe returned that has the open high low close volume and timestamp is here. This corresponds to one of the elements in bars1['data']

[{'o': 191.46,
  'c': 190.64,
  'h': 191.52,
  'l': 189.74,
  'v': 260274.08,
  't': 1700577000000}]

I tried

   print(pd.to_datetime(1700577000000}))

and got something from 1970-01-01 00:28:20.577000 It should be a data point from 2023 as the request was for 10w weeks and 1 day bars


Solution

  • I suppose this is UNIX timestamp in milliseconds, if you know it is from 2023 the value should be 1700577000 since the value of 170057700000 gives the year 55859 and pd.to_datetime gives OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 55859-02-21 04:00:00. If you know the fact that data should be from 2023 , and all other timestamps are also 13 digit numbers just divide the time stamp by 1000 as @user19077881 suggested to convert the timestamp to seconds.

    Here is the alternative way to convert unix timestamp to desired string datetime format :

    Input:

    import datetime
    t = 1700577000000
    datetime.datetime.utcfromtimestamp(t//1000).strftime('%m/%d/%Y (%H:%M:%S)')
    

    Output:

    '11/21/2023 (14:30:00)'