Data Format
This document describes the data format used by timezonefinder library, including the data sources, design rationales, and performance optimizations.
For detailed statistics of the current dataset in use, see Data Report. For how these structures are consumed at query time - and for the design decisions behind them - see Architecture.
Data Source
The timezone boundary data used in timezonefinder is sourced from the timezone-boundary-builder project.
This project compiles timezone boundaries from OpenStreetMap data and makes them available as GeoJSON files.
Dataset version timezones-with-oceans: Currently the boundaries with ocean time zones and the full original dataset are being used.
Note
In the data set the timezone polygons often include territorial waters -> they do NOT follow the shorelines.
This makes the results of certain_timezone_at() less expressive:
from a timezone match one cannot distinguish whether a query point lies on land or in ocean.
Note
Please note that timezone polygons might be overlapping (cf. e.g. timezone-boundary-builder/issue/105)
and that hence a query coordinate can actually match multiple time zones.
timezone_at() returns one of them: the zone with the smaller spherical area, i.e. the one
enclaved in the other (see overlapping-zone precedence below).
timezones_at() returns all of them, with that same zone first (see Usage).
The processing pipeline for this data involves:
Downloading the latest
timezones-with-<...>.geojson.zipfile from the releases section of the timezone-boundary-builder repositoryUnzipping into the
combined.jsonfileRenaming it after the release it came from (
combined-2026c.json), which nothing inside the file recordsRunning the
file_converter.pyscript to compile the data into the binary format used bytimezonefinder
The script update_data.sh automates this process. It resolves the release tag first and names the download after it (combined-with-oceans-2026c.json), since a release archive says nothing about which release it is - the converter reads the tag back off that name, and refuses an unpacked archive that lacks it rather than compiling data that could never say where it came from. The tag is also recorded in the repository’s DATA_VERSION file. The script further regenerates the committed benchmark input fixtures under tests/fixtures/benchmarks/ (see scripts/generate_benchmark_fixtures.py), since some of those fixtures (on-land/shortcut classification, point-in-polygon polygon IDs) are derived from this boundary data and are pinned to the DATA_VERSION they were generated against.
Between the conversion and those fixtures, the script states what the new data answers: scripts/data_update_guard.py re-answers a frozen sample of 10,000 on-land points and rewrites the committed baseline under tests/fixtures/data_update/, so a release is reviewed as a text diff of timezone names rather than as a change in binary size. The sample is frozen and separate from the benchmark fixtures precisely because those are regenerated by the same run. An ordinary refinement release moves no answers at all; above 5 % the release is still prepared but is refused, and the weekly pipeline opens it as a draft that nothing merges - so the answers that moved are reviewed as a normal pull request diff and a person decides. The same run also compares the compiled boundary and hole payloads against the sizes the previous release recorded, and refuses the dataset the same way when either moves more than a few percent - which catches a release that lost or gained a whole part of itself, the one failure a sample of points can miss. The baseline describes the full dataset with oceans - the one the released distribution is built from - so the guard skips any other --dataset variant instead of comparing it against answers a different set of zones produced.
Alternative Dataset Options
The update_data.sh script also supports downloading the reduced timezones-now dataset (via --dataset=same-since-now), which merges timezones with identical behavior (as of now) into a single zone. That leaves a few dozen zones instead of several hundred, and a correspondingly smaller memory footprint - upstream’s own lookup of which zones it merges into which is vendored at tests/fixtures/reduced_zones/mapping.json, and states the exact figures for the release this checkout declares. However, this dataset:
Provides incorrect data for observed timekeeping methods in the past at certain locations
Loses location-specific information (e.g.,
Europe/BerlinbecomesEurope/Paris)Reduces localization capabilities
If your use case requires the reduced dataset, you can use the update_data.sh script to download and process the timezones-with-oceans-now.geojson file.
Data Structure Overview
Where the data lives
The compiled binaries ship in their own distribution, timezonefinder-data (installed
automatically with timezonefinder), and are reached through timezonefinder_data.DATA_DIR -
which is what timezonefinder.configs.DEFAULT_DATA_DIR resolves to. Any other directory of the
same shape works just as well: pass it as bin_file_location (see use cases).
That distribution’s major version is the data format generation
(timezonefinder.configs.DATA_FORMAT_VERSION), and its next two components name the
upstream release: 3.2026.3 is format 3 built from 2026c. A PEP 440 post-release suffix
identifies revised compiled contents from the same source, so 3.2026.3.post1 is still built
from 2026c rather than implying an upstream 2026d release. timezonefinder requires
timezonefinder-data>=…,<N+1, so a dataset update needs no code release while a format change is
refused when resolving rather than when reading. Bumping either per-file layout_version below
requires bumping DATA_FORMAT_VERSION too.
The timezonefinder library uses highly optimized binary data structures to enable fast and memory-efficient timezone lookups. The data is organized into several files:
Polygon Coordinates: Stored in a FlatBuffers binary file (
coordinates.bin) one for all timezone boundary polygons and one for all holes, as bit-packed residuals against a per-block coordinate frame (see Block Coordinate Frames). The hole file holds only the rings that are not a copy of a boundary polygon (see Holes as Boundary References)Shortcut Index: Spatial index over an aligned grid tree (
shortcuts.bin) holding, per cell, either the timezone that covers it or the polygons a lookup there has to testNumpy Arrays: Various NumPy binary files (.npy) storing information about the polygons
Zone Names: Text file listing the timezone names
Hole Registry: a mapping from polygon IDs to the amount and position of its holes
Schemas: a copy of the FlatBuffers schema definitions the binaries above were written by, under
schemas/
hole_registry.json maps each boundary polygon ID to [hole count, first hole ID].
Those half-open ranges form one exact partition of the dense hole-ID space: no hole is
missing or owned twice, and every registered hole ring lies inside the boundary that
names it. timezonefinder validate-data establishes these properties before a custom
directory is used; lookups can then address the ranges directly without repeating the
geometry work.
Coordinate Representation
All coordinates (longitude and latitude) are held as 32-bit integers scaled by 10^7. This transformation:
Makes computations faster
Requires significantly less storage space
Maintains high accuracy (see the two grids below)
Two grids, and the difference matters
The encoding resolves 10-7 degrees - a tenth of a microdegree, not a
microdegree. At the equator, where a degree of longitude is longest and the ground error
of a fixed angular step is therefore worst, that is ~1.11 cm. This is the grid a
query is placed on, by timezonefinder.utils.coord2int(), which truncates toward
zero - so a caller’s own coordinate can be a whole step from its stored form rather than
half of one.
The boundary data resolves 10-6 degrees, ~11.1 cm, because that is what
timezone-boundary-builder publishes: six decimal places, never seven. Measured over
3,589,489 coordinate literals of the 2026c release, the decimal places published are
{1: 307, 2: 2064, 3: 12778, 4: 57575, 5: 430811, 6: 3085954}. The packaged data sits
on that grid exactly - every one of its 15,850,626 values is a multiple of ten
tenth-of-a-microdegree steps - and is stored in units of it, which is where ~6.4 MB of
Block Coordinate Frames went. The conversion rounds rather than truncating, so a
packaged coordinate is the vertex upstream published rather than one step short of it;
scripts.utils.source_coord2int refuses an input carrying a seventh decimal rather
than rounding real information away.
The two are independent. The boundary can be stored as coarsely as its source allows
while a query stays as fine as int32 allows, because the kernel scales a residual up
into the query’s units rather than rounding the query down into the boundary’s - see
Block Coordinate Frames.
Why 1.11 cm is a ceiling rather than a defect:
The spacing is even. A fixed-point integer resolves the same amount at the antimeridian as at Greenwich, which a float does not.
It is already finer than the data it is compared against, by a factor of ten, and there is no headroom to go further: ±180° at 10-7 uses 1.8 × 109 of
int32’s 2.15 × 109, so a ten-times-finer grid would need 64-bit coordinates.
The width is set by the range, not by the precision. Covering ±180° at 10-7 needs 3.6 × 109 distinct values, which is 32 bits - but so does 10-6, at 3.6 × 108. No precision a boundary dataset could plausibly want brings the global range inside int16, whose 65,536 values over 360° would be 610 m apart. Which is why storing the coarser grid saves nothing in a fixed-width layout and ~6.4 MB in the variable-width one this format uses: only an encoding able to charge per value can charge less for a narrower one.
For scale in the other direction, consecutive vertices of the packaged polygons are a median 47.6 m apart, and only 0.02 % of edges are shorter than the source’s own 11.1 cm step. Coordinate precision and vertex density are separate axes, and neither is the binding constraint on accuracy at a border.
The figures are derived, not quoted: timezonefinder.utils.coordinate_resolution() returns the representable step of a dtype and timezonefinder.utils.degrees_to_metres() converts it to ground distance, and tests/test_coordinate_precision.py holds every claim on this page to what they compute.
Storage |
Step (degrees) |
At the equator |
Against the packaged data |
|---|---|---|---|
|
1.0e-07 (everywhere) |
1.11 cm |
— |
|
2.8e-14 |
3.2 nm |
~3,500,000× finer |
|
1.5e-05 |
1.70 m |
~153× coarser |
|
1.25e-01 |
13.9 km |
unusable |
float64 is therefore the narrowest IEEE float that preserves what the packaged data holds, which is why it is what the lookup converts its input to.
float32 fails twice over: its step at the antimeridian is 153 times the stored resolution, and 180 × 107 exceeds its exact-integer range (224), so the scaling itself would lose bits.
float64 represents that product exactly, well inside 253.
The consequence for a caller is under the batch lookups: coordinates handed over as float32 can be rounded across a border before the lookup ever runs.
Those integers are what a coordinate means; they are not how one is stored. A ring is held as bit-packed residuals against one coordinate frame per block, which is described under Block Coordinate Frames - and the ray-casting kernels never rebuild an absolute coordinate at all, because every quantity their predicate forms is a difference of two of them.
Data Files
The library creates and uses the following files:
Polygon Data
coordinates.bin: FlatBuffer binary file containing all polygon coordinates, one packed payload per ring (see Block Coordinate Frames)block_ranges.npy,block_offsets.npy: the latitude block index over those coordinates (see Latitude Block Index)block_bases.npy,block_widths.npy,nr_vertices.npy: what decodes a payload - the coordinate frame each block’s residuals are relative to, and the ring sizes a packed payload’s length does not give (see Block Coordinate Frames)zone_ids.npy: NumPy array mapping polygon IDs to timezone IDs. Stored as unsigned integers (uint16by default,uint8for datasets with less than 256 timezones); pass--zone-id-dtypetoscripts/file_converter.pyor set the environment variable theTIMEZONEFINDER_ZONE_ID_DTYPEenvironment variable when compiling custom data to override the default.zone_positions.npy: NumPy array indicating where each timezone’s polygons start and end
Boundaries Information
xmin.npy,xmax.npy,ymin.npy,ymax.npy: NumPy arrays storing the bounding boxes for each polygon
Hole Data
poly_ref.npy: NumPyint32array, one entry per hole, saying where that hole’s ring is stored (see Holes as Boundary References)
Spatial Indexing
shortcuts.bin: the spatial index, mapping every cell of the grid tree to either the zone that covers it or the boundary polygons a lookup there has to test. Its layout is described under Shortcut Index Layout.
Other Files
schemas/*.fbs: the FlatBuffers schema definitions describing the binaries in this directory, copied fromtimezonefinder/flatbuf/schemas/when the data is compiled. A data directory that carries the definition of its own format can be read back without the package that wrote it. Generated, never hand-edited:timezonefinder._data_integrity.validate_shipped_schemasholds the copy to the original both in the converter and over the committed data
Note
The two extensions are not interchangeable. .fbs is the FlatBuffers schema
extension and is used here only for schema definitions; the serialised buffers are
.bin, and each says what it is through the file identifier in its first bytes
rather than through its name.
timezone_names.txt: List of all timezone namesdata_version.txt: the timezone-boundary-builder release this data was compiled from, asTimezoneFinder.data_versionreports it. Taken from the input’s filename (combined-with-oceans-2026c.json), or fromfile_converter.py --data-versionfor an input that cannot carry it. Data that is not a release at all - your own GeoJSON - is stampedunknown
Latitude Block Index
Ray casting flips the inside/outside parity only on an edge that spans the query
latitude: the kernel’s test (y > y1) ^ (y > y2) is exactly
min(y1, y2) < y <= max(y1, y2). An edge that does not span it contributes nothing,
however far the ray otherwise travels - and in a ring of nearly 200,000 vertices, almost
none of them do.
So every ring is split into fixed blocks of consecutive vertices, and the range of latitudes each block’s edges span is stored beside the coordinates. A block whose range excludes the query latitude provably holds no flipping edge and is skipped whole.
File |
What it holds |
|---|---|
|
|
|
|
A block owns the edges leaving its own vertices, so its last edge reaches the first vertex of the next block - and on the final block, wraps to vertex 0. That bridging vertex is included in the range, which is what makes every edge lie inside exactly one block’s stored range.
POLYGON_BLOCK_SIZE (timezonefinder/configs.py) is 128 vertices per block. It is
chosen by measurement rather than by intuition, and the two sides of the trade run
opposite ways: smaller blocks bound a ring’s latitudes more tightly and skip more of it,
larger blocks decide that in fewer comparisons.
scripts/tune_block_size.py re-runs the sweep over whatever data is packaged.
Nothing in the files records the size they were built at, so it is part of what the
polygon layout version means - a directory blocked at another size is rejected by the
layout marker in coordinates.bin, and by
timezonefinder._data_integrity.validate_block_index where the data is produced.
What it costs is one int32 pair per block - about 0.5 MB against 38 MB of
coordinates - and one comparison for the 30 % of polygons small enough to fit in a
single block. What it buys is the long tail: the slowest queries this package answers
are one ray cast across a very large ring, and
Timezone Finding Performance Benchmark carries the distribution.
Where a ring starts
Blocks partition a ring from its first vertex, so where a stored ring starts changes how tightly its blocks bound it - and nothing downstream depends on that choice. The canonical key used to match holes against boundaries is rotation-invariant, the bounding boxes are unaffected, and a hole kept as a reference follows its boundary automatically. The converter therefore rotates each ring to the start index that minimises the expected scan, and stores nothing to record it: no reader can tell, and none needs to.
The objective is deliberately query-independent. For a latitude drawn uniformly from a
ring’s own range - which is what a bounding-box check has already narrowed a query to -
the expected number of edges scanned is sum(edges in block × block span) / total
span, so minimising the numerator minimises the expected scan without the builder ever
seeing a query. Each block is weighted by the number of edges it holds, which
matters because the final block is ragged: for a ring of 129 vertices it holds one edge
against the first block’s 128, and weighting the two equally would trade a large real
cost for a tiny one. All rotations are searched, not one block of them, since rotating
by a whole block moves that ragged block and so repartitions the ring rather than
relabelling it. It is worth ~9 % of the edges a query scans - real, but well below what
the benchmark suite can resolve, which is why it is taken as a free step of a rebuild
that was happening anyway rather than claimed as a speedup.
The two rules that suggest themselves both lose: starting at the minimum-latitude vertex costs 1.026x the edges of the unrotated order and the maximum-latitude one 1.010x. The reason is the bridging vertex - the last block’s bridge wraps to vertex 0, so putting a latitude extreme there stretches exactly that block.
Searching every rotation would be quadratic done directly. It is linear in the number of blocks instead: the span of every window is computed once for all start positions, and each rotation is then a gather and a sum over those. That is ~12 s for the whole collection, in a converter that takes about a minute.
A consequence worth knowing: get_geometry returns each ring starting at the vertex
the converter chose, which is not the one the upstream GeoJSON began with. The ring is
the same closed path either way.
Block Coordinate Frames
Storing a coordinate as a fixed 32-bit absolute spends the same 32 bits on a vertex in Luxembourg as on the span of the Pacific, and a block of 128 consecutive vertices of a boundary ring covers very little ground. So each block carries its own frame - the minimum x and y its vertices take - and holds them as residuals against it, in as many bits as that block’s own span needs.
A residual counts steps of the grid the source is published on, not of the finer grid a
coordinate is stored in. timezone-boundary-builder states boundaries to six decimal
places, so every packaged coordinate is a multiple of ten of the tenth-of-a-microdegree
units above (SOURCE_COORD_STEP), and dividing by it is exact - it takes a further
log2(10) ~ 3.3 bits off every field. What it costs is one multiply where a residual is
read, and a hard requirement that compiled data sit on that grid, which
scripts.utils.source_coord2int enforces at conversion time.
Together those take boundaries/coordinates.bin from 63,423,696 to 31,735,692
bytes, and the whole compiled directory from ~64.6 MB to ~31.9 MB.
The blocks are exactly the ones Latitude Block Index already partitions a ring into. Nothing new is cut, and no query does more work deciding what to read: the same range comparison decides whether a block is touched at all, and only a surviving block is unpacked.
File |
What it holds |
|---|---|
|
one payload per ring: a stream of 32-bit words, blocks in ring order |
|
|
|
|
|
|
Within a block the x residuals come first, then the y ones, each region starting on a
word boundary; residual k occupies bits [k*w, (k+1)*w) of its region, least
significant bit first. The word alignment is what lets a kernel read any field with two
loads: a field is at most 32 bits wide and starts at most 31 bits into a word, so two
consecutive words always hold it. Addressing the payload by byte instead makes the
same read five dependent byte loads, which measured 2.2x the whole kernel on the numba
backend - the alignment costs ~2 bytes per region and buys that back.
A block stores its bridging vertex - the first vertex of the next block, wrapping to vertex 0 on the last - exactly as the latitude index includes it in its range. That is what keeps a block self-contained: both endpoints of every edge it owns are inside it, so no edge is ever read through two frames.
The y origin costs nothing to read: a kernel has already loaded block_ranges[b][0]
to decide whether the block survives the latitude test at all. What it costs instead is
a check that cannot be made after the fact - a lower bound that is also a frame origin
cannot be re-derived from a decode that used it - so the converter refuses to encode a
block whose latitudes its index does not describe, and that is where the two are held
together.
Why the query moves instead of the vertices
Nothing is reconstructed. Every quantity the ray-casting predicate forms is a
difference of two coordinates, so subtracting a block’s origin from the query point
once is exact and the origin is never added back per vertex: x2 - xq computed in the
frame is x2_absolute - x. The arithmetic therefore stays inside the same bounds
the unpacked kernel documents, and the answers are identical rather than merely close -
the packed kernel is checked against the
unpacked one over the real query pairs the committed fixtures produce.
Two consequences worth knowing. get_geometry() decodes, so it costs a pass over the
ring rather than handing out a view - it is not a lookup path and never was. And
in_memory=True holds the packed payload rather than pre-decoded rings, which is the
same code path as the mapped mode with a heap buffer instead of a mapping, at roughly
half the resident bytes decoded rings would take.
Two grids, and the difference matters. The encoding is unchanged: a coordinate is still a 32-bit integer scaled by 107, and a query is still placed on that grid and compared against the boundary exactly. The boundary data sits on the coarser grid its source is published on - six decimal places, ~11 cm - and always did: the seventh digit was never information. What changed is that the packaged file now says so, instead of storing a seventh digit that was an artifact of the conversion.
That conversion is the second half. It moved the boundary toward its source rather than
away from it. coord2int truncates toward zero,
which is right for a query and wrong for the source - it stored the vertex upstream
publishes as 13.358 as 133579999, 1.1 cm short, on 6.27 % of all coordinates.
The converter rounds onto the source’s own grid now, so the packaged boundary is the
published boundary. No vertex is dropped and no ring is redrawn - this is not
simplification, it is the removal of a conversion error.
timezonefinder._data_integrity.validate_block_payload re-derives every frame from its own
decode, in the converter against the rings it was given and in the test suite over what
the repository ships, and tests/test_coordinate_precision.py holds the packaged
coordinates to the source grid.
Holes as Boundary References
Almost every hole in the dataset is an enclave: the upstream boundary builder cuts a hole into the surrounding zone using exactly the ring it also emits as the enclosed zone’s own boundary polygon. Both rings describe the same closed path, so storing the hole ring a second time is pure redundancy — it is the same geometry under two IDs.
poly_ref.npy records, per hole ID, which of the two cases applies. The sign carries
the discriminant, so no separate table and no ambiguous sentinel value is needed:
value |
meaning |
|---|---|
|
the hole ring is boundary polygon |
|
the ring is stored inline, at index |
Both index spaces are dense and start at zero, which is why the inline case is offset by
one: without it, inline ring 0 would encode as -0 == 0 and collide with boundary
polygon 0.
Two properties keep this cheap at runtime:
Hole IDs stay dense. Every hole ID remains valid, so the hole registry and all of its consumers are untouched by the change.
The bounding box vectors stay valid verbatim. A referenced ring is identical to the boundary ring, so its bounding box already equals the boundary’s. The bounding box rejection test — the hot path — keeps reading a flat array with no indirection; only the coordinate lookup gains a branch, and only where a point in polygon test was about to happen anyway.
Matching is done on a canonical form of the ring (rotated to its lexicographically smallest vertex, compared in both winding directions), with bounding box and vertex count equality as a prefilter only. It compares the integer coordinates themselves rather than any derived quantity, so there is no tolerance involved: two rings either trace the same closed path or they do not.
A consequence worth knowing: a referenced hole ring is handed back exactly as the
boundary polygon stores it, which for part of the dataset means a different starting
vertex or winding direction than the hole ring originally had. The closed path — and
therefore every point in polygon result and every timezone answer — is unchanged, but
get_geometry() may report those hole rings starting
at a different vertex than an older release did.
Holes without a twin
A small remainder (27 of 756 in release 2026c) matches no boundary polygon and stays
stored inline. These are mostly ocean zones (Etc/GMT±XX) cut by a hole whose area is
covered by a union of several land zones rather than by any single polygon, plus the
Asia/Jerusalem enclaves.
They are kept rather than dropped, and so is every other hole. Probing their interiors shows every one of them is in fact covered by other zones, so dropping them would not leave a gap — but coverage only says the right zone is among the candidates, and what decides the answer is whether it is reached first.
That ordering cannot be guaranteed, and the reason is structural rather than a property of one release. Dropping holes would need a precedence relation over zones — “where these two both cover a point, this one is the answer” — and the relation the packaged geometry demands is cyclic: seven zone pairs each have to precede the other. Every one is a second-order enclave, a zone inside a zone inside the first zone again — Baarle-Hertog and its Dutch counter-enclaves, Nahwa inside Madha inside the UAE, the Hopi reservation inside the Navajo Nation. Precedence is a relation between zones while containment is a relation between rings, and two levels of nesting map two opposite ring relations onto one zone pair. Both Dubai/Muscat witnesses lie inside the same hole, so not even a per-hole rule breaks the tie.
Measured consequences, on release 2026c: dropping every hole changes 1,404 of 6,048
hole-interior answers and 2 of 20,000 uniformly random ones, and dropping only these 27
still breaks 20 of them. prototypes/hole_removal_impact.py measures that,
prototypes/hole_precedence_relation.py derives the relation and its cycles, and
tests/test_hole_lookup_regression.py checks interior points of every hole against the
geometry so a future attempt fails loudly.
FlatBuffers Schema
The library uses the Google FlatBuffers binary file format for the polygon coordinate data.
The schemas are defined in the timezonefinder/flatbuf/schemas/*.fbs files.
coordinates.bin and shortcuts.bin both carry a file identifier and a layout_version, both checked when the file is opened; a mismatch raises a ValueError naming the offending file instead of silently returning wrong timezones. coordinates.bin uses the identifier TZFP, and its layout_version records the coordinate encoding and, for a hole collection, whether it holds every ring or only the ones that are not references (see Holes as Boundary References). shortcuts.bin uses TZSC.
layout_version tracks what the file holds, not the package version, and is bumped only when that actually changes. Data compiled by any release that writes a given layout is readable by any release that reads it, so a directory passed to bin_file_location does not need regenerating on an ordinary upgrade - only when the changelog reports a data format change, or when you want newer boundary data.
Note that this check covers those two files only. The NumPy arrays carry no such marker yet, so mixing those across a format change is still undetected.
Spatial Indexing with an Aligned Grid Tree
The Spatial Indexing Backbone
The shortcut index is the backbone of the timezonefinder package and its performance. It drastically reduces the number of polygons that need to be checked to determine which timezone a point is located in.
How it works:
The surface of the Earth is divided into a dense grid of square cells aligned with longitude and latitude: 480 columns by 240 rows, so 0.75 degrees a side
Each cell gets one of three answers:
Unique zones: when every polygon reaching the cell belongs to the same timezone, the zone ID is stored directly
Several zones: the cell is refined into a 4 by 4 block of children, 0.1875 degrees a side, and each child is asked the same question
Several zones in a child too: the child stores an array of polygon IDs to test
- When looking up a timezone for a specific point, the library:
Divides the point’s integer coordinates by the cell width, one division per axis
Reads the entry for that cell
If it is a zone ID, returns the timezone immediately
If it names a block, repeats the division one level finer and reads again
If it is a polygon array, tests only those polygons
This provides several performance benefits:
Reduced search space: instead of checking all polygons (thousands), only a small subset needs to be evaluated — the large majority of random queries need no polygon test at all
No search for the cell: the cell is two integer divisions per level, so finding it touches no memory and needs no key array
Memory efficiency: two bytes per cell, and the finer cells exist only where zones meet, so the open ocean costs one entry per 0.75 degrees rather than per 0.1875
Vectorised batches:
timezone_ids_at()resolves a whole batch’s cells in a handful of NumPy operations, which is most of why a batch lookup is worth using
Why these cells
Two properties of the cells carry the index’s performance, and both are about the cells rather than about how they are stored:
A cell is arithmetic. Finding it is a floor division per axis of coordinates the lookup has already scaled, so it touches no memory and needs no key array — and a batch of them is one NumPy expression, which is most of why a batch lookup is worth using.
A cell is tight. The cells are defined in the same integer coordinates the point-in-polygon kernel reads, and each owns its north and east edges and not its south or west — the kernel’s own convention. So a zone whose polygons only reach across a cell edge is not a candidate inside it. Fewer candidates per cell means fewer cells that need geometry at all. The rule never leaves out a polygon the kernel can place a cell’s point inside; it does admit one whose interior enters the cell without reaching any of its integer points, a sliver under ~1.1 cm wide, which costs that cell one bounding-box rejection.
Alignment matters too: the ocean timezones meet on the 7.5 degree meridians, and a grid whose cell edges fall on them does not mix two ocean zones into one cell.
The shape — how coarse the root grid is, how many levels it refines, and how large a block is — is a measured choice within the 800 KB index cap, each candidate compiled from the packaged boundaries and answered through the real query path. Under full refinement the finest cell width sets how many polygons a lookup tests, and every level costs a batch lookup one more pass, so the shipped tree reaches the finest cells the cap allows in a single level. Two refusals are worth knowing, because they are the obvious shapes to reach for: a flat grid of the finest cells, which spends two bytes on every cell of the open ocean, and a deeper or selectively refined tree, which tests fewer polygons and is slower per batch. contributing/improvements/decisions/longitude-latitude-aligned-index-decisions.md records the sweep and every refusal.
The tightness rests on the kernel’s edge convention, which tests/test_point_in_polygon_boundary_convention.py pins on every kernel. A kernel change moving boundary points to the other polygon would make these cells misanswer one-unit strips along every aligned border while every sampled test still passed, so that test is what this layout is built on.
The two lines no polygon owns as spelled are handled before the division: -180 degrees reads as +180, which is the last column rather than the first, and -90 as the point one unit north, which is row 0. docs/result_stability.rst says why, and tests/test_minus_180_meridian_and_minus_90_parallel.py fails on a tree that clamps the longitude instead of wrapping it.
The shortcuts are precompiled during the data build process. This preprocessing step is computationally intensive but only needs to be performed once, allowing all subsequent timezone lookups to be extremely fast. scripts/grid_cells.py holds the candidate rule, what it guarantees and where it over-includes.
Shortcut Index Layout
shortcuts.bin holds five arrays after a 56-byte header. The header is the file
identifier TZSC, a uint32 layout version, and six int64: the root column
count and the block side the index was built for, how many child blocks it stores, the
number of distinct candidate lists, and the widths chosen for the two data-dependent
columns.
The grid shape is in the header because nothing else in the file records it, and it changes what every cell means without changing anything a reader would notice - the layout is identical at every shape, so the layout version cannot cover it. A reader built for another grid is refused rather than allowed to answer with another cell’s timezone.
array |
dtype |
indexed by |
holds |
|---|---|---|---|
|
|
root cell |
the answer for that cell, or which block refines it |
|
|
child cell, |
the answer for that cell |
|
narrowest that fits |
distinct candidate list |
CSR offsets into |
|
|
every distinct candidate list, back to back |
|
|
narrowest that fits |
distinct candidate list |
where the candidate loop may stop |
The cell is the index, and it is arithmetic. Each level is a whole number of
coordinate units wide, because 0.75 and 0.1875 degrees both divide the integer
longitude span exactly. A cell owns (c * w, (c + 1) * w] of its axis - its north and
east edges and not its south or west - so with x the point’s scaled integer longitude
and w the level’s width:
column = (x + 180 * COORD2INT_FACTOR - 1) // w
row = (y + 90 * COORD2INT_FACTOR - 1) // w
cell = row * columns_at_this_level + column
No keys are stored and no search runs at lookup time. The whole descent is written out per level rather than looped, because a Python call per level costs more than the level saves.
The two levels hold the same tri-state. One int16 each:
>= 0- the zone id, and the whole answer. The large majority of cells.== -1- no cell here. Custom data can leave cells uncovered, so this is a real state; the packaged ocean zones cover every cell.< -1- intable, child block-(value + 2); inblocks, candidate list-(value + 2).
A negative value therefore means a block on one level and a candidate list on the other,
and nothing in the number says which: the level does. That is why the root table may
never carry a candidate list, and why timezonefinder/_data_integrity.py checks each
level’s negative values against the array they address.
-1 is free for “absent” because a stored candidate list can never have length 1: a
lone candidate is unambiguous and is therefore stored as a zone id instead.
Because a cell the tree answers reads nothing else, bounds and last_change are
indexed by distinct candidate list rather than by cell - far fewer of them, and the
cells that never read them cost nothing.
Each distinct candidate list is stored once. Cells with identical lists carry equal
offsets into the shared payload, not an index to a shared entry, so a repeated list costs
a lookup exactly what a unique one costs. The distinct lists are packed back to back, so
one CSR array of n+1 bounds carries both starts and ends and no length column exists
to disagree with it.
``last_change`` is ``get_last_change_idx`` precomputed. It depends only on the candidate list, so it deduplicates with everything else and costs one byte per distinct list to take a scan off every ambiguous query.
The tested prefix may interleave zones. Only the final zone must occupy a
complete, untested suffix. During conversion, scripts/shortcut_ordering.py
reduces integrated expected full-predicate work, including bounding boxes, the
union box enclosing all holes, individual hole checks and latitude-active blocks.
No query points are sampled: the piecewise cost proxy is integrated analytically
against spherical surface area over clipped polygon geometry. The module gives
the formulas, search algorithm, cost coefficients and geometric approximations.
Final zones are enumerated; greedy candidates and adjacent exchanges improve on
the zone precedence order as the incumbent. This is a heuristic for general point-dependent costs,
with an exact ratio-order special case for constant costs and disjoint polygons.
There is no candidate-count cutoff. Geometry safety gates preserve zone
precedence where necessary while allowing within-zone polygon optimization.
This changes no candidate membership or binary layout. It does change the
fallback heuristic used by TimezoneFinderL.
A cell is now its own rectangle, so the gate’s envelope is exact rather than a circumscribed spherical cap, and no cell has to be refused for sitting at a pole or at the antimeridian the way a cap-derived envelope did.
Overlapping-zone precedence is a conversion rule of its own: where two zones’ polygons overlap, the zone with the smaller spherical area comes first, so the answer in an overlap is the enclave in every cell. It is computed once per zone from the geometry, with the timezone identifier breaking an exact tie, and is the order the ordering pass starts from and keeps wherever the gate refuses; the pass does not infer precedence from cost. Replacing covered ambiguous cells by direct answers is a separate conversion decision. A coverage pass can run first, leaving only its remaining ambiguous cells to order.
The two data-dependent widths are chosen by fit, not by headroom. An overflow surfaces
where the data is built rather than in a user’s process - provided something checks, which
is what timezonefinder/_data_integrity.py does, over what the converter just wrote and over
what is committed, naming the value, the ceiling, the width to move to and the version
bumps that follow. The two fixed int16 levels are guarded the same way, and the block
index is the one that answers first as a dataset grows: a root table that cannot name all
its blocks is fixed by a finer root grid before it is fixed by a wider column.
A lookup, in full:
v = table[root_cell] # two divisions, one read
if v >= 0: return v # the common case
if v == -1: return None
v = blocks[(-v - 2) * 16 + child] # two more divisions, one more read
if v >= 0: return v
if v == -1: return None
i = -(v + 2) # several zones: the candidate list, plus
return payload[bounds[i]:bounds[i + 1]] # last_change[i] for where to stop
Why the index makes no polygon redundant
Roughly three quarters of the cells resolve to a single zone ID, and a query answered from one of those reads no geometry at all. That invites an optimisation: if some boundary polygon were only ever reached through such cells, its coordinates would sit in boundaries/coordinates.bin serving nothing, and could be dropped — accepting that get_geometry() could then only report its bounding box.
No such polygon exists. Every boundary polygon appears in at least one ambiguous cell, and a large share of them appear in exactly one — which is what makes the idea look plausible in the first place.
This is structural rather than a property of a particular release or cell shape. The packaged data covers the globe, so any cell that a polygon’s rim passes through also holds area outside that polygon; that area belongs to a different zone, unless a polygon of the same zone abuts it there — which dissolved multipolygons do not do. Cell size never enters the argument, so a finer index does not create such polygons either. It only makes the rim cells smaller.
The nearest claim that is true concerns testing rather than candidacy: because timezone_at stops at the last zone change in the candidate list and returns the final zone untested, a polygon can be a candidate everywhere and still never be handed to the point-in-polygon kernel. In release 2026c that describes 206 of the 1,322 boundary polygons, around a sixth of all vertices. Their coordinates are kept regardless, for reasons that are worth stating because the conclusion is easy to reach and wrong:
Most of them are hole rings. 175 of the 206 are the ring some hole is stored as a reference to (see Holes as Boundary References), so their coordinates serve the surrounding polygon’s hole test, which is very much performed.
The remainder are the largest polygons in the dataset. A zone that is the biggest in every cell listing it is, by construction, a mainland — the 31 survivors are around a sixth of all vertices, and include the main polygons of
America/Toronto,Europe/Berlin,Europe/MoscowandAsia/Shanghai. A bounding box is not a degraded outline of those: it averages well over twice the polygon’s own area, soget_geometry()would answer a rectangle largely covering other countries, in the same return type and without an error.certain_timezone_at()degrades further still — it tests every candidate with no early break, so with the ring gone it would match nothing and returnNoneacross most of the zone.It would make an API’s output depend on the index. Which polygons qualify follows from which cells happened to come out unique and from how shortcut candidates happened to be sorted. The index is a candidate filter, free to be reordered, rebuilt or replaced — including its cells. Deriving
get_geometry’s output from its structure would turn an index change into a silent change in what the geometry API returns.
This is the boundary-polygon counterpart of Holes without a twin, and it fails in the same way: covering the query path is not the same question as covering the public API.
Design Rationales
Several key design decisions make timezonefinder extremely efficient:
Binary Data Format: All data is stored in optimized binary formats (FlatBuffers and NumPy arrays) for fast loading and minimal memory footprint
Integer Coordinates: Converting floating-point coordinates to integers improves computational speed and reduces memory usage
Spatial Indexing: The aligned grid-tree spatial index drastically reduces the search space for polygon containment tests
Memory Mapping: Binary files be read fully into memory with the setting
in_memory=True
Advantages
The data format and algorithms used by timezonefinder provide several key advantages:
Speed: Timezone lookups are extremely fast, also see speed tests
Memory Efficiency: The library has a small memory footprint due to its binary data format and memory mapping
Accuracy: The boundary data is stored at the ~11 cm resolution its source publishes, on a coordinate grid ten times finer than that, despite the space-saving optimizations
Offline Operation: No internet connection is required for lookups
Cross-platform: The binary format works across different operating systems and architectures