Search code examples
pythoncryptocurrencyccxt

How to set time zone for historical price quotes retrieved using ccxt?


The python example below from ccxt will fetch historical price quotes.

https://github.com/ccxt/ccxt/blob/master/examples/py/binance-fetch-ohlcv-to-csv.py

The code does not show how to set the time zone. How can I set the fetched price quote timestamp to Asian HK/Singapore time zone?

I am using python 3.9


Solution

  • I think you can just pass datetime string with timezone like 2017-08-17T00:00:00+08:00 into scrape_candles_to_csv function from your example ([Asian HK/Singapore has UTC+8 timezone)

    Method exchange.parse8601 correctly handled strings with timezone

    >>> exchange.parse8601('2017-08-17T00:00:00+08:00')
    1502899200000
    >>> exchange.parse8601('2017-08-17T00:00:00Z')
    1502928000000
    

    So I ran

    scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1h', '2021-12-17T00:00:00+08:00', 100)
    

    And got

    100 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-20T19:00:00.000Z
    200 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-24T23:00:00.000Z
    260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
    260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
    Saved 260 candles from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z to binance.csv
    

    binance.csv

    1639670400000,48578.61,48717.43,48302.49,48506.58,1778.62433
    1639674000000,48506.57,48520.73,48060.0,48084.14,1593.51908
    1639677600000,48084.15,48313.29,47862.6,47983.5,1434.94112
    1639681200000,47983.49,48129.67,47666.0,47866.01,1763.75104
    1639684800000,47866.01,48387.54,47832.34,47929.53,1510.25811
    1639688400000,47929.53,48167.75,47900.0,48089.61,766.62189
    1639692000000,48089.61,48167.84,47511.0,47821.27,1428.35052
    1639695600000,47821.27,47821.27,47532.86,47632.38,1046.44879
    ...
    

    The first timestamp 1639670400000 equals 2017-08-17T00:00:00+08:00