Howwise RSS
Trading Software5 min read

ccxt OHLCV Timestamp Timezone: Convert to HK or SG Time

Short answer

The ccxt OHLCV timestamp is the candle open time in UTC epoch milliseconds, and ccxt has no timezone setting. Convert it yourself with pd.to_datetime(ts, unit='ms', utc=True).dt.tz_convert('Asia/Hong_Kong').

Key takeaways
  • ccxt fetch_ohlcv returns integer epoch milliseconds (UTC), so the only place to apply a timezone is your own code after fetching.
  • In pandas always pass utc=True to to_datetime before tz_convert, otherwise the result is naive and tz_convert raises a TypeError.
  • Converting timestamps never moves 1d candle boundaries: Binance daily candles still open at 00:00 UTC, which is 08:00 HKT or SGT.
  • A local-time since value must be turned into UTC epoch ms, and parse8601 treats a string without an offset as UTC.
  • Store tz-aware UTC and convert only for display, charts or reports.

Does ccxt have a timezone setting for OHLCV timestamps?

No. fetch_ohlcv returns rows of [timestamp, open, high, low, close, volume], and timestamp is an integer count of milliseconds since 1970-01-01 00:00:00 UTC. An epoch value has no zone attached, so there is nothing for ccxt to configure. Helpers such as exchange.milliseconds() and exchange.iso8601(ms) are also UTC.

The timestamp is the candle open time, not the close. A 1h candle stamped 10:00 UTC covers 10:00:00 to 10:59:59.999 UTC. Remember this whenever you reason about sessions in local time.

Timezone work therefore happens in two places: converting results after fetching, and converting a local time into UTC ms before passing since.

How do I convert ccxt timestamps to Hong Kong or Singapore time with pandas?

Build the DataFrame, parse the integers as UTC, then convert. Hong Kong and Singapore are both UTC+8 with no daylight saving, so only the zone name differs.

import ccxt, pandas as pd

ex = ccxt.binance()
rows = ex.fetch_ohlcv('BTC/USDT', '1h', limit=500)
df = pd.DataFrame(rows, columns=['timestamp','open','high','low','close','volume'])

# keep a UTC column for storage and joins
df['ts_utc'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
# display columns
df['ts_hk'] = df['ts_utc'].dt.tz_convert('Asia/Hong_Kong')
df['ts_sg'] = df['ts_utc'].dt.tz_convert('Asia/Singapore')
print(df[['timestamp','ts_utc','ts_hk']].head(2))
Warning: Without utc=True, to_datetime returns a naive datetime64 column and .dt.tz_convert raises 'Cannot convert tz-naive timestamps, use tz_localize to localize'. Do not fix it with tz_localize('Asia/Hong_Kong') on the naive value: that labels UTC clock times as HKT and shifts every candle by 8 hours. Use tz_localize('UTC') if you must, then tz_convert.

How do I convert a timestamp in pure Python with zoneinfo?

zoneinfo is in the standard library from Python 3.9. On Windows there is no system timezone database, so run pip install tzdata. On 3.8 use pytz or pip install backports.zoneinfo.

The classic mistakes are forgetting that the values are milliseconds and omitting tz. datetime.fromtimestamp(ms/1000) without tz silently uses the machine's local zone, so the same script gives different output on a laptop and a UTC server. datetime.utcfromtimestamp returns a naive datetime, which later comparisons with aware objects reject.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

ms = 1704067200000
HK = ZoneInfo('Asia/Hong_Kong')

utc = datetime.fromtimestamp(ms / 1000, tz=timezone.utc)
hk = datetime.fromtimestamp(ms / 1000, tz=HK)
print(utc.isoformat())  # 2024-01-01T00:00:00+00:00
print(hk.isoformat())   # 2024-01-01T08:00:00+08:00

# candle close time for a 1h candle (open + period - 1 ms)
close_hk = hk.timestamp() * 1000 + 3600_000 - 1

How do I pass a local-time since to fetch_ohlcv?

since must be UTC epoch milliseconds, so midnight in Hong Kong has to be converted first. A naive datetime(2024,1,1).timestamp() would use the machine zone, so always attach a zone.

exchange.parse8601 is convenient, but a string with no offset is read as UTC. '2024-01-01T00:00:00' means 08:00 HKT, not midnight HKT. Include +08:00 explicitly.

from datetime import datetime
from zoneinfo import ZoneInfo
import ccxt

ex = ccxt.binance()
HK = ZoneInfo('Asia/Hong_Kong')

since = int(datetime(2024, 1, 1, tzinfo=HK).timestamp() * 1000)
# equivalent
since2 = ex.parse8601('2024-01-01T00:00:00+08:00')
assert since == since2 == 1704038400000

rows = []  # every candle collected so far
batch = ex.fetch_ohlcv('BTC/USDT', '1h', since=since, limit=1000)
rows += batch

# paginate: advance past the last open time of the previous batch
while len(batch) == 1000:
    last = batch[-1][0]
    batch = ex.fetch_ohlcv('BTC/USDT', '1h', since=last + 1, limit=1000)
    rows += batch
Tip: Use int(...) on the result. A float since can be rejected or truncated by some exchanges.

Why do my daily candles still open at 08:00 after converting?

The exchange decides candle boundaries, not your display zone. Most exchanges, Binance included, align 1d candles to 00:00 UTC, which is 08:00 HKT or SGT. Converting the label shows 08:00 and does not change which trades are inside the candle.

Some venues offer other daily alignments. Binance's raw klines endpoint accepts a timeZone parameter, but ccxt support for it is limited and varies by version, so do not rely on it without testing.

The portable fix is to fetch 1h or finer data and resample after converting. Daily bars from local midnight then contain trades from 00:00 to 23:59 HKT.

FieldUTCHong Kong (UTC+8)
Raw ccxt value17040672000001704067200000
1d candle open2024-01-01 00:00:00+00:002024-01-01 08:00:00+08:00
1d candle close (open + 1d - 1 ms)2024-01-01 23:59:59.999+00:002024-01-02 07:59:59.999+08:00
Local-midnight daily bar needs1h data from 16:00 previous day UTC1h data from 00:00
h = df.set_index('ts_utc')[['open','high','low','close','volume']].tz_convert('Asia/Hong_Kong')

daily_hk = h.resample('1D').agg({
    'open': 'first', 'high': 'max', 'low': 'min',
    'close': 'last', 'volume': 'sum'})
# bars now start at 00:00 HKT. For another start, e.g. 08:00:
# h.resample('1D', offset='8h')
# Drop the last bar if it is still incomplete.
Warning: Resampling to local days needs complete hourly data. Gaps in the 1h series produce wrong opens and closes without any error, so check for missing timestamps first.

How should I write the CSV and store the data?

Fetch, convert, then write. Keep the UTC epoch column in storage and add a formatted local column for people. Dropping the zone with tz_localize(None) after converting leaves clock times nobody can interpret later, and merging such files with another exchange's UTC data misaligns rows.

pandas writes tz-aware datetimes to CSV with the offset, such as 2024-01-01 08:00:00+08:00. Excel often shows that as text, so format explicitly if the file is for spreadsheets.

import ccxt, pandas as pd

ex = ccxt.binance()
rows = ex.fetch_ohlcv('BTC/USDT', '1h', limit=1000)
df = pd.DataFrame(rows, columns=['timestamp','open','high','low','close','volume'])

ts = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['datetime_hkt'] = ts.dt.tz_convert('Asia/Hong_Kong')

# Excel friendly text, no offset (label the column with the zone)
out = df.copy()
out['datetime_hkt'] = out['datetime_hkt'].dt.strftime('%Y-%m-%d %H:%M:%S')
out.to_csv('btc_1h.csv', index=False)

# or keep the offset in ISO text
df.to_csv('btc_1h_iso.csv', index=False, date_format='%Y-%m-%dT%H:%M:%S%z')

How do I verify the conversion and handle DST zones?

Pick one candle and compare it with the exchange chart. The web UI uses the browser's time zone, so set the chart to UTC or your own zone, then match the open price and the open time. Remember the chart label is the open time, which matches ccxt.

HK and SG have no daylight saving, so a fixed +08:00 offset would work, but named zones remain safer if the code is reused. For zones with DST such as America/New_York, one local hour is repeated in autumn and one is missing in spring. Converting from UTC is always safe, while converting local to UTC can be ambiguous, which is another reason to keep storage in UTC.

For session logic such as a market open at 09:30 local, compute in the local zone but remember each row is an open time. A 1h candle stamped 09:00 HKT ends at 09:59:59.999 and does not include the 09:30 open as its start.

Common questions

How do I get the current time in Hong Kong with ccxt?

ccxt only gives UTC: exchange.milliseconds() returns epoch ms. Convert with datetime.fromtimestamp(ex.milliseconds()/1000, tz=ZoneInfo('Asia/Hong_Kong')).

Why is my ccxt timestamp 13 digits?

It is milliseconds since the Unix epoch, not seconds. Divide by 1000 for datetime functions, or pass unit='ms' to pandas.

Can I use a fixed +08:00 offset instead of a zone name?

Yes for Hong Kong and Singapore, since neither observes daylight saving. A named zone such as Asia/Hong_Kong is still preferable because it keeps working if the code is reused for another region.

Is the ccxt OHLCV timestamp the open or close time?

It is the open time. Add the timeframe length minus 1 ms to get the last millisecond of the candle, for example 3,599,999 ms for 1h.

Why does tz_convert fail with a tz-naive error?

The column was created without utc=True, so pandas holds naive datetimes. Recreate it with pd.to_datetime(..., unit='ms', utc=True), or call tz_localize('UTC') first, then tz_convert.

Related topics:ccxtpandastimezoneohlcvpython