pub struct Timedelta;Implementations§
Source§impl Timedelta
impl Timedelta
pub const NANOS_PER_MICRO: i64 = 1_000
pub const NANOS_PER_MILLI: i64 = 1_000_000
pub const NANOS_PER_SEC: i64 = 1_000_000_000
pub const NANOS_PER_MIN: i64
pub const NANOS_PER_HOUR: i64
pub const NANOS_PER_DAY: i64
pub const NANOS_PER_WEEK: i64
pub const NAT: i64 = i64::MIN
pub fn parse(s: &str) -> Result<i64, TimedeltaError>
Sourcepub fn unit_to_nanos(unit: &str) -> Option<i64>
pub fn unit_to_nanos(unit: &str) -> Option<i64>
Map a pandas-style frequency-alias string to a nanosecond-count.
Recognizes pandas’s offset alias core set plus common word forms:
W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
nanosecond(s)/N. Empty string maps to days (matches pandas default).
Returns None for unrecognized aliases — callers can choose to map
that to NaT (consistent with the rest of fp-types) or surface as a
typed error.
Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
downstream crates can consume the same alias map fp-types uses for
Timedelta::from_unit / Timestamp::*_to_unit.
pub fn components(nanos: i64) -> TimedeltaComponents
pub fn total_seconds(nanos: i64) -> f64
Sourcepub fn as_unit(nanos: i64, unit: &str) -> f64
pub fn as_unit(nanos: i64, unit: &str) -> f64
Convert to specified time unit.
Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
Sourcepub fn days(nanos: i64) -> Option<i64>
pub fn days(nanos: i64) -> Option<i64>
Return the days component, or None for NaT. Matches
pd.Timedelta.days.
⚠️ None, NOT 0, AND THE TYPE IS THE FIX
(br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
component helpers used to return 0 for NaT, one of them behind a
comment asserting “pandas returns 0 for NaT.days (no error)”. MEASURED,
live pandas 2.2.3: pd.NaT.days is nan, and
pd.to_timedelta([1, None, -1], unit='s').dt.days is float64
[0.0, nan, -1.0] — pandas promotes the whole column because NaN cannot
live in int64.
An i64 return cannot express that, so correctness depended on every
caller remembering to test NAT first. It did — timedelta_component
checked in three separate arms — but that is a convention, and the bead
filed it as a landmine for the next person to wire a .dt accessor: a
function whose doc says “matches pandas” handing back a plausible integer
where pandas has a missing value. Option<i64> moves the fact into the
type, so a caller cannot forget and the duplicated NAT tests go away.
Sourcepub fn seconds(nanos: i64) -> Option<i64>
pub fn seconds(nanos: i64) -> Option<i64>
Return the seconds component (0-86399), or None for NaT. Matches
pd.Timedelta.seconds. See Self::days for why this is an Option.
Sourcepub fn microseconds(nanos: i64) -> Option<i64>
pub fn microseconds(nanos: i64) -> Option<i64>
Return the microseconds component (0-999999), or None for NaT.
Matches pd.Timedelta.microseconds. See Self::days.
Sourcepub fn nanoseconds(nanos: i64) -> Option<i64>
pub fn nanoseconds(nanos: i64) -> Option<i64>
Return the nanoseconds component (0-999), or None for NaT. Matches
pd.Timedelta.nanoseconds. See Self::days.
Sourcepub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution
pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution
The coarsest TimedeltaStringResolution that renders nanos
losslessly. Fold over a column with max.
NaT reports Days, the identity of that fold, because pandas excludes
it from the scan: [1 days, NaT] still renders ['1 days', 'NaT'].
Sourcepub fn format_at_resolution(
nanos: i64,
resolution: TimedeltaStringResolution,
) -> String
pub fn format_at_resolution( nanos: i64, resolution: TimedeltaStringResolution, ) -> String
Render nanos the way astype(str) does, at a resolution chosen for the
whole column by Self::string_resolution.
The Full arm is Self::format verbatim — the per-value sub-second
width was already right. Only the Days arm is new, and it exists
because a column of whole days drops its time part completely:
'1 days', not '1 days 00:00:00'.
pub fn format(nanos: i64) -> String
Sourcepub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError>
pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError>
Build a nanosecond Timedelta from a float quantity of unit.
Matches pd.Timedelta(value, unit=...):
NaN→NAT. pandas returnsNaT, andNATis how NaT is spelled in this i64 representation. Rust’s float→intasmapsNaNto 0, so the unguarded cast used to hand back a ZERO DURATION for a missing value (br-frankenpandas-8v92m).- non-finite or out-of-range product →
TimedeltaError::Overflow. pandas raisesOutOfBoundsTimedelta(“Cannot cast inf from s to ‘ns’ without overflow”); theascast used to SATURATE toi64::MAX, returning a finite, plausible ~106751-day duration instead. - unknown unit →
TimedeltaError::InvalidFormat, unchanged.
The overflow guard is the same one parse and the component parser
already use (added by br-frankenpandas-zw3mg, which fixed two of the
three sites sharing this expression and missed this one).
Sourcepub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure>
pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure>
Add two Timedelta nanosecond values, reporting overflow.
br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
overflow — a NaT operand yields Ok(NAT), exactly as before. Only an
unrepresentable result is an Err.
§Errors
PandasTemporalError::Overflow when the sum exceeds i64.
Sourcepub fn add(a: i64, b: i64) -> i64
pub fn add(a: i64, b: i64) -> i64
Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
Sourcepub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure>
pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure>
Subtract two Timedelta nanosecond values, reporting overflow.
§Errors
PandasTemporalError::Overflow when the difference exceeds i64.
Sourcepub fn sub(a: i64, b: i64) -> i64
pub fn sub(a: i64, b: i64) -> i64
Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
Sourcepub fn neg(a: i64) -> i64
pub fn neg(a: i64) -> i64
Negate a Timedelta value. NaT stays NaT.
There is no overflow case to handle, and the saturating_ call is a
belt-and-braces no-op: the only i64 whose negation overflows is
i64::MIN, and i64::MIN IS the NaT sentinel, so it is consumed by
the guard above. The representable range is [i64::MIN + 1, i64::MAX],
which is symmetric about zero.
CORRECTED br-frankenpandas-fyr1z: this used to claim “pandas:
-pd.Timedelta.min is NaT since min == -max - 1 cannot be negated”.
That is false in both halves. pandas’ Timedelta.min.value is
-9223372036854775807 == -Timedelta.max.value, NOT -max - 1
(-max - 1 is i64::MIN, which pandas also reserves for NaT), and
live pandas 2.2.3 returns Timedelta('106751 days 23:47:16.854775807')
— i.e. Timedelta.max — for -pd.Timedelta.min, abs(pd.Timedelta .min), and the vectorized -Series[timedelta64] / .abs() forms.
Do not “fix” this to return NaT; that would be the parity regression.
Sourcepub fn abs(a: i64) -> i64
pub fn abs(a: i64) -> i64
Absolute value of a Timedelta. NaT stays NaT.
As with Timedelta::neg, no overflow is reachable: i64::MIN is the
NaT sentinel and is consumed by the guard, and |i64::MIN + 1| is
exactly i64::MAX. pandas agrees — abs(pd.Timedelta.min) is
Timedelta.max, not NaT.
Sourcepub fn mul_scalar(a: i64, factor: i64) -> i64
pub fn mul_scalar(a: i64, factor: i64) -> i64
Multiply a Timedelta value by an integer factor. NaT propagates; overflow → NaT (see the overflow note above).
Matches pandas pd.Timedelta(...) * int, which raises OverflowError
rather than returning a saturated duration.
Sourcepub fn mul_scalar_with_policy(
a: i64,
factor: i64,
policy: OverflowPolicy,
) -> i64
pub fn mul_scalar_with_policy( a: i64, factor: i64, policy: OverflowPolicy, ) -> i64
Multiply a Timedelta by an integer factor under an explicit policy.
br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: STRICT REPRODUCES PANDAS’ SILENT WRAP. The rationale is that this is a PORT — STRICT means bit-for-bit observable parity with the incumbent including its quirks, so the wrap is a deliberately reproduced pandas behaviour, not a defect of ours.
Verified against live pandas 2.2.3: Series([Timedelta.max]) * 2 returns
-2 ns (displayed -1 days +23:59:59.999999998), which is exactly
i64::MAX.wrapping_mul(2). Rust’s wrapping arithmetic reproduces numpy’s
int64 wraparound bit-for-bit, so no emulation is needed.
The wrap is INTEGER-MULTIPLIER ONLY: Series * 2.0 returns NaT in
pandas, so a float multiplier must not route here.
Every other policy keeps today’s behaviour — NaT, with HARDENED also recording the recovery. So the fail-open shape br-frankenpandas-lgyy8 removed is reachable ONLY when a caller explicitly asks for STRICT incumbent parity, never by default. See DISC-020.
Sourcepub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure>
pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure>
Multiply a Timedelta value by an integer factor, reporting overflow.
§Errors
PandasTemporalError::Overflow when the product exceeds i64 — which
is what the SCALAR pd.Timedelta.max * 2 raises. Note DISC-018: the
VECTORIZED Series * int wraps silently instead, so a strict arm for
this op must decide per-surface rather than inherit this class blindly.
Sourcepub fn div_scalar(a: i64, divisor: i64) -> i64
pub fn div_scalar(a: i64, divisor: i64) -> i64
Floor-divide a Timedelta value by an integer divisor. NaT propagates. Returns NaT on divide-by-zero (matches pandas, which raises, but we surface as NaT to avoid panics at the type-system boundary).
Matches pandas / Python pd.Timedelta(...) // int: floor division,
not truncation toward zero. -100 // 3 == -34, and 100 // -3 == -34. Rust’s / truncates toward zero and div_euclid keeps the
remainder non-negative — neither matches pandas when the divisor is
negative. This helper adjusts trunc-toward-zero into floor.
Sourcepub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure>
pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure>
Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
failure and yields Ok(NAT); only a zero divisor is an Err.
⚠ SCALAR SEMANTICS ONLY. pandas raises ZeroDivisionError for the
scalar pd.Timedelta('1s') // 0, but the VECTORIZED
Series([Timedelta]) // 0 returns NaT (both probed on 2.2.3). The
infallible Self::div_scalar above keeps the NaT behavior that the
vectorized callers depend on, and a STRICT arm must route only the
scalar surface here.
§Errors
PandasTemporalError::ZeroDivision when divisor == 0.
Sourcepub fn div_timedelta(a: i64, b: i64) -> f64
pub fn div_timedelta(a: i64, b: i64) -> f64
Divide two Timedelta values, returning the ratio as f64.
Matches pandas pd.Timedelta(...) / pd.Timedelta(...) → float.
NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
Sourcepub fn isoformat(nanos: i64) -> String
pub fn isoformat(nanos: i64) -> String
Returns ISO 8601 duration format string.
Matches pandas pd.Timedelta.isoformat(). Returns format like
“P1DT2H3M4.567890123S” for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
A negative duration is pandas’ components form: whole days rounded
down, then a non-negative clock (-1 day -1 hour is “P-2DT23H0M0S”;
it was “-P1DT1H0M0S”). NaT returns “NaT”.
Sourcepub fn floor(nanos: i64, freq: &str) -> i64
pub fn floor(nanos: i64, freq: &str) -> i64
Rounds down to the nearest frequency unit.
Matches pandas pd.Timedelta.floor(freq). NaT is preserved.
Sourcepub fn ceil(nanos: i64, freq: &str) -> i64
pub fn ceil(nanos: i64, freq: &str) -> i64
Rounds up to the nearest frequency unit.
Matches pandas pd.Timedelta.ceil(freq). NaT is preserved; overflow
→ NaT (pd.Timedelta.max.ceil('D') raises OutOfBoundsTimedelta: Cannot round ... without overflow, so a clamped i64::MAX would be a
fabricated finite duration — see br-frankenpandas-kyd16).