Intraday Market Data Time Zone and Daylight Saving Fixes
Fix intraday market data time zone and daylight saving problems by storing everything as tz-aware UTC, localizing naive vendor timestamps with an IANA zone, and converting to the exchange zone only for session logic.
- Store, join and key every bar on tz-aware UTC, and convert to an IANA exchange zone such as America/New_York only to decide sessions and trading days.
- Before trusting any vendor, find what its naive timestamps mean by checking where the 09:30 ET opening volume spike lands.
- tz_localize on a naive index needs explicit ambiguous and nonexistent arguments, and ambiguous='infer' only works on sorted, contiguous data.
- A fixed UTC session filter breaks twice a year, and the US and EU change clocks on different dates, so filter in exchange-local time.
- Validate every load: monotonic unique index, 390 one-minute bars on a full US day, 210 on a half day, and a measured vendor offset of zero minutes.
What is the rule for intraday market data time zones and daylight saving?
The safest intraday market data time zone is UTC. Keep one canonical representation: timezone-aware UTC (dtype datetime64[ns, UTC]). Join, sort, deduplicate and store on that. UTC has no daylight saving, so it can never produce a duplicate or missing hour.
Convert to the exchange zone (America/New_York, Europe/London, Asia/Tokyo) only for session logic, daily keys and display. Always use IANA names. Abbreviations like EST and fixed offsets like -05:00 are correct for only part of the year, which is exactly how an hour-off bug appears in July.
Use zoneinfo from the standard library, not pytz. With pytz, passing tzinfo= to a datetime constructor silently uses a historical LMT offset, and localize() is needed. zoneinfo behaves like normal Python. Also avoid datetime.utcnow(), which is deprecated and returns a naive object. Use datetime.now(timezone.utc).
How do I find out what a vendor's naive timestamps mean?
Do not guess. A naive timestamp can be UTC, exchange local time, the vendor's server time, or a fixed offset. Run the diagnosis below before writing any conversion.
The open-spike test works because US equity volume is highest in the first minutes of the regular session. Whatever zone the timestamps are in, the spike must land on 09:30 New York time on both a summer day and a winter day.
- Print df.index.tz and df.index.dtype. datetime64[ns, UTC] is aware; plain datetime64[ns] is naive and its meaning is unknown.
- Pick a liquid symbol and two dates, one in July and one in January. Group 1-minute volume by the time-of-day of the raw index and find the peak bar.
- If the peak is at 09:30 on both dates, the data is exchange local. If it is at 14:30 in winter and 13:30 in summer, it is UTC. If it is at the same clock time on both dates (for example 14:30 year round), the vendor uses a fixed offset or ignores DST.
- Check whether the first bar of the session is labeled 09:30 (bar start) or 09:31 (bar end). See the labeling section below.
- Record the finding as per-vendor metadata (source_tz, label) and never infer it again at load time.
import pandas as pd
def open_spike(df, day):
d = df.loc[day] # naive or aware index, string slice
return d['volume'].groupby(d.index.time).sum().idxmax()
print(df.index.tz, df.index.dtype)
print(open_spike(df, '2025-07-15'), open_spike(df, '2025-01-15'))Why does tz_localize raise errors around DST changes?
tz_localize attaches a zone to naive wall-clock times. tz_convert translates an already aware index to another zone. Calling tz_localize on an aware index raises TypeError, and calling tz_convert on a naive one raises too. Comparing or joining naive with aware also raises TypeError, while comparing two naive indexes from different zones succeeds silently and gives wrong results.
Local clock times are not unique on two nights. On fall-back night (US: first Sunday of November) 01:00 to 02:00 happens twice, so a naive 01:30 is ambiguous. On spring-forward night (US: second Sunday of March) 02:00 to 03:00 never happens, so a naive 02:30 is nonexistent. pandas raises AmbiguousTimeError or NonExistentTimeError unless you say what to do.
| Argument | Value | Behavior | Use when |
|---|---|---|---|
| ambiguous | 'infer' | Detects the repeated hour from order; first pass is DST, second is standard | Sorted, contiguous 24h data such as futures or FX |
| ambiguous | bool array | True means DST (first occurrence), False means standard | You know the order, for example from a vendor flag or row position |
| ambiguous | 'NaT' | Ambiguous times become NaT | Data in that hour is not needed; drop afterward |
| ambiguous | 'raise' | Raises AmbiguousTimeError (default) | You want to fail loudly |
| nonexistent | 'shift_forward' / 'shift_backward' | Moves to the nearest valid time | Rare stray stamps in the gap |
| nonexistent | 'NaT' | Becomes NaT | Treat such rows as corrupt |
| nonexistent | 'raise' | Raises NonExistentTimeError (default) | Strict validation |
What does a tested normalize_to_utc function look like?
The function below localizes naive input, converts aware input, sorts, drops duplicates and returns UTC. Sources that are already UTC or epoch based skip the DST logic entirely. The session filter works in exchange-local wall time and returns only regular trading hours for start-labeled bars.
import pandas as pd
from zoneinfo import ZoneInfo
def normalize_to_utc(df, source_tz=None):
idx = pd.DatetimeIndex(df.index)
if idx.tz is None:
if source_tz is None:
raise ValueError('naive index: source_tz is required')
df = df.sort_index()
idx = pd.DatetimeIndex(df.index)
try:
idx = idx.tz_localize(source_tz, ambiguous='infer',
nonexistent='raise')
except Exception:
# fall back: mark ambiguous rows NaT and drop them (data loss!)
idx = idx.tz_localize(source_tz, ambiguous='NaT',
nonexistent='NaT')
else:
idx = idx.tz_convert('UTC')
out = df.copy()
out.index = idx.tz_convert('UTC')
out = out[out.index.notna()]
out = out.sort_index()
out = out[~out.index.duplicated(keep='last')]
return out
def rth(df, tz='America/New_York', start='09:30', end='15:59'):
loc = df.index.tz_convert(tz)
pos = loc.indexer_between_time(start, end) # local wall clock
return df.iloc[pos]
# DST-edge tests (1-minute, start-labeled bars)
for day, first_utc in [('2025-03-07', '14:30'), ('2025-03-10', '13:30'),
('2025-10-31', '13:30'), ('2025-11-03', '14:30')]:
ix = pd.date_range(f'{day} 00:00', f'{day} 23:59', freq='1min',
tz='UTC')
d = rth(pd.DataFrame({'x': 1}, index=ix))
assert len(d) == 390
assert d.index[0].strftime('%H:%M') == first_utcWhy does a fixed UTC session filter break twice a year?
The 09:30 to 16:00 ET session is 14:30 to 21:00 UTC in winter and 13:30 to 20:00 UTC in summer. A hard-coded 14:30 to 21:00 UTC filter is therefore an hour late all summer, cutting the open and including post-market bars.
Regions switch on different dates. The US moves on the second Sunday of March and first Sunday of November. The EU moves on the last Sunday of March and October. Between the two spring changes the New York to London gap is 4 hours instead of 5, and the same happens for a few days in autumn. Most of Asia has no DST, so Tokyo is always UTC+9. Australia is in the southern hemisphere and shifts in the opposite direction (its summer time runs roughly October to April).
This means a cross-market join on a constant offset breaks, and a London open appears to shift relative to New York. Filter each market in its own IANA zone.
| Date (2025) | Event | NY open in UTC | London open (08:00) in UTC |
|---|---|---|---|
| Mar 7 (Fri) | US and EU on standard time | 14:30 | 08:00 |
| Mar 10 (Mon) | US on DST, EU not yet; NY-London gap 4h | 13:30 | 08:00 |
| Apr 1 (Tue) | Both on DST | 13:30 | 07:00 |
| Oct 28 (Tue) | US on DST, EU back to standard; gap 4h | 13:30 | 08:00 |
| Nov 3 (Mon) | Both on standard time | 14:30 | 08:00 |
How do I align bar labels and build daily bars?
Vendors label bars by their start (a 09:30 bar covers 09:30:00 to 09:30:59) or by their end (the same bar is stamped 09:31). Mixing them creates a consistent one-bar shift that looks like a time zone problem. Check the first RTH bar: a start-labeled series has its first bar at 09:30 and last at 15:59, an end-labeled one runs 09:31 to 16:00.
Convert everything to a single convention, usually start-labeled, with df.shift(freq='-1min') for end-labeled minute data. In pandas resampling, use label='left', closed='left' for start-labeled bars. For an aware index, resample bins are computed in the index zone, so daily or 30-minute bins on a UTC index align to UTC, not to the exchange. Use origin='start_day' on an exchange-local index, or offset='30min' to anchor bins to 09:30.
For daily bars, group on the exchange-local date, not the UTC date. A UTC date split puts the evening of a Tokyo session or a late US after-hours bar on the wrong day.
| Market | Trading-day key | Code |
|---|---|---|
| US equities | Local date in America/New_York | idx.tz_convert(tz).date |
| Crypto | UTC date | idx.normalize() |
| FX (17:00 NY roll) | Local time plus 7h, then date | (loc + pd.Timedelta('7h')).date |
| CME-style futures (18:00 ET open) | Local time plus 6h, then date | (loc + pd.Timedelta('6h')).date |
loc = df.index.tz_convert('America/New_York')
df['day'] = (loc + pd.Timedelta('6h')).date # futures trading day
per_day = df.groupby('day').size()
# local calendar days for 24h instruments: 23h on 2025-03-09, 25h on 2025-11-02
hours = df.groupby(loc.date).size() / 60
assert hours.loc[pd.Timestamp('2025-11-02').date()] > 24 How do I validate alignment across vendors and in storage?
Run a checklist on every load and fail the job when it breaks. Then check storage, because a CSV round-trip drops tz and brings back the original ambiguity.
- Assert df.index.tz is not None, index.is_monotonic_increasing and index.is_unique.
- Count bars per exchange-local day: 390 one-minute RTH bars on a full day, 210 on a half day, 0 on holidays.
- For 24h instruments, confirm the local day is 23 hours on 2025-03-09 and 25 hours on 2025-11-02, and that those lengths appear nowhere else.
- After an inner join of two vendors, compute the offset: for lag in range(-120, 121), correlate returns a.pct_change() with b.pct_change().shift(lag). The best lag should be 0. An offset of 60 means a DST error and 1 means a label mismatch.
- Compare first-bar and last-bar timestamps per day for both vendors. They should match up to the labeling rule.
- Write to Parquet with UTC-aware timestamps (timestamp[ns, tz=UTC]) and keep exchange_tz in symbol metadata or a column. Never store local time strings, and reload with explicit parse options if you must use CSV.
Common questions
Should pandas data be stored in UTC or exchange time?
Store UTC. It is unambiguous, sorts correctly and joins across vendors without any DST handling. Convert to the exchange zone in memory only when you need a session filter, trading-day key or chart labels.
Why is my data one hour off only in some months?
The vendor or your code is applying a fixed offset such as UTC-5 or EST, which is right in winter and wrong in summer. Switch to the IANA zone and run the open-spike test on a July and a January date. The peak must stay at 09:30 local.
How do I convert UTC to America/New_York for intraday bars in pandas?
Use df.index = df.index.tz_convert('America/New_York') on an aware UTC index. If the index is naive and known to be UTC, first call tz_localize('UTC'). Do the conversion on a copy and keep the UTC column for storage and joins.
Does between_time work on a tz-aware index?
Yes. between_time and indexer_between_time compare the local wall-clock time of the index zone. Convert to the exchange zone first, then filter with '09:30' and '15:59' for start-labeled minute bars. Filtering a UTC index with those strings returns the wrong hours.
What happens to the repeated hour on fall-back night in my data?
If it is UTC or epoch data, nothing, as both hours have distinct timestamps. If it is naive local time, the two hours share clock values, so you need ambiguous='infer' or a bool array, otherwise pandas raises or drops them. Naive data without order information cannot be recovered reliably.