← tsb playground
toTimedelta stats
Convert scalars, arrays, or Series values to
Timedelta objects — mirroring
pandas.to_timedelta().
Supported input formats
| Format | Example | Result (ms) |
| Pandas-style | "1 days 02:03:04" | 93 784 000 ms |
| Clock (HH:MM:SS) | "01:30:00" | 5 400 000 ms |
| ISO 8601 | "P1DT2H" | 93 600 000 ms |
| Human-readable | "1h 30m 20s" | 5 420 000 ms |
| number (unit="ns") | 1_000_000_000 | 1 000 ms |
| number (unit="ms") | 5000 | 5 000 ms |
| Timedelta | new Timedelta(1000) | unchanged |
| null / undefined / NaN | null | null |
Timedelta class
| Property / Method | Description |
.totalMs | Total duration in milliseconds (signed) |
.days | Whole days |
.hours | Hours within the current day (0–23) |
.minutes | Minutes within the current hour (0–59) |
.seconds | Seconds within the current minute (0–59) |
.ms | Milliseconds within the current second (0–999) |
.abs() | Absolute value |
.add(other) | Add two Timedeltas |
.subtract(other) | Subtract a Timedelta |
.scale(n) | Multiply by a scalar |
.lt(other) | Less-than comparison |
.gt(other) | Greater-than comparison |
.eq(other) | Equality comparison |
.toString() | Pandas-style string representation |
Error handling
| errors= | Behaviour |
"raise" (default) | Throws TypeError on unparseable input |
"coerce" | Returns null on unparseable input |
"ignore" | Returns the original value unchanged |
Quick examples
import { toTimedelta, Timedelta, formatTimedelta, Series } from "tsb";
// Scalar — various string formats
toTimedelta("1 days 02:03:04"); // Timedelta(93_784_000 ms)
toTimedelta("01:30:00"); // Timedelta(5_400_000 ms)
toTimedelta("P1DT2H3M4S"); // ISO 8601
toTimedelta("1h 30m 20s 500ms"); // human-readable
// Scalar — numeric
toTimedelta(1_000_000_000); // default unit "ns" → 1000 ms
toTimedelta(5000, { unit: "ms" }); // 5000 ms
toTimedelta(2, { unit: "D" }); // 2 days
// Missing values
toTimedelta(null); // null
toTimedelta("nope", { errors: "coerce" }); // null
toTimedelta("nope", { errors: "ignore" }); // "nope" (unchanged)
// Timedelta arithmetic
const a = toTimedelta("1h") as Timedelta;
const b = toTimedelta("30m") as Timedelta;
a.add(b).toString(); // "0 days 01:30:00"
a.subtract(b).totalMs; // 1_800_000
// Array
toTimedelta(["1h", "30m", null]);
// => [Timedelta(3_600_000), Timedelta(1_800_000), null]
// Series
const s = new Series({ data: ["1h", "30m", null] });
toTimedelta(s);
// => Series<Timedelta | null> with dtype=timedelta
// formatTimedelta
formatTimedelta(new Timedelta(86_400_000 + 3_661_000));
// => "1 day 01:01:01"
Python / pandas equivalent