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
- Both frames must be sorted on the join key.
strategypicks backward, forward or nearest.- It is how you attach the last known price or setting.
Keywords and builtins used here
asprint
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.
Step 2 of 5 in Reshaping & joining, step 16 of 32 in Polars.