---
title: Out-of-time train/test split
url: https://gurkanozkan.ai/learn/coding/mle-out-of-time-train-test-split-04/
markdown: https://gurkanozkan.ai/learn/coding/mle-out-of-time-train-test-split-04.md
kind: coding
difficulty: Easy
topics:
  - Leakage
  - Evaluation
  - Time series
json: https://gurkanozkan.ai/api/learn/coding/mle-out-of-time-train-test-split-04.json
robots: noindex
---

# Out-of-time train/test split

Given row timestamps and `test_fraction`: - Let `n = len(timestamps)` and `k = floor(n·(1 − test_fraction))`. - If `k ≥ n`, everything is train. - Otherwise `cutoff` is the k-th smallest timestamp (0-based, in sorted order). Train is all indices with timestamp `< cutoff`; test is all indices with timestamp `≥ cutoff`. This guarantees no timestamp appears on both sides. Return `(train_indices, test_indices)`, each ascending.

## Signature

```python
def time_split(timestamps: list[int], test_fraction: float) -> tuple[list[int], list[int]]: ...
```

## Examples

Each call and the value it should give.

```python
>>> time_split([5,1,4,2,3], 0.4) == ([1, 3, 4], [0, 2])
True

>>> time_split([1,2,2,2,3], 0.4) == ([0], [1, 2, 3, 4])
True
```

## Hints

1. Sort timestamps, compute the k-th cutoff.
2. k = floor(n * (1 - test_fraction)); if k >= n, everything is train.
3. Train is everything < cutoff, test is everything >= cutoff — ties must fall on one side.

## Reference solution

```python
import math

def time_split(timestamps, test_fraction):
    n = len(timestamps)
    if n == 0:
        return [], []
    s = sorted(timestamps)
    k = int(math.floor(n * (1 - test_fraction) + 1e-12))
    if k >= n:
        return list(range(n)), []
    cutoff = s[k]
    train = [i for i, t in enumerate(timestamps) if t < cutoff]
    test = [i for i, t in enumerate(timestamps) if t >= cutoff]
    return train, test
```

## What a strong solution covers

- Splits on time, not rows, and keeps ties on one side.
- Handles empty input and the fractions 0 and 1.
- Discusses adding a gap or embargo for delayed labels, and group-aware splits.

## Common mistakes

- a random shuffle split
- splitting at a row position so equal timestamps fall on both sides.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
