typestar

Joining on nearest time in Python

join_asof matches each left row to the most recent right row.

from datetime import datetime

import polars as pl

runs = pl.DataFrame({
    "at": [datetime(2026, 7, 29, 9, 5), datetime(2026, 7, 29, 9, 40)],
    "tpm": [104, 96],
}).sort("at")

settings = pl.DataFrame({
    "at": [datetime(2026, 7, 29, 9, 0), datetime(2026, 7, 29, 9, 30)],
    "theme": ["default", "monokai"],
}).sort("at")

print(runs.join_asof(settings, on="at", strategy="backward"))

How it works

  1. Both frames must be sorted on the join key.
  2. strategy picks backward, forward or nearest.
  3. It is how you attach the last known price or setting.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
376
Tokens
149
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 2 of 5 in Reshaping & joining, step 16 of 32 in Polars.

← Previous Next →