From 87e60790e09b14dfda68f2011ade8b5608c4ebba Mon Sep 17 00:00:00 2001 From: Cody Wyatt Neiman Date: Wed, 2 Dec 2026 15:54:44 +0000 Subject: [PATCH 1/2] bench: date_trunc in each time unit, with and without a timezone Extend the date_trunc benchmark from nanosecond and second timestamps without a timezone to every time unit, with and without a timezone, at second, hour, day, week, month, quarter and year granularity. The existing benchmarks keep their names and inputs. Co-Authored-By: Claude Opus 5.5 --- .../datetime_expressions/date_trunc.rs | 67 +++++++++++++++---- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/datafusion/functions/benches/datetime_expressions/date_trunc.rs b/datafusion/functions/benches/datetime_expressions/date_trunc.rs index fcee07556faa9..a65697c07d751 100644 --- a/datafusion/functions/benches/datetime_expressions/date_trunc.rs +++ b/datafusion/functions/benches/datetime_expressions/date_trunc.rs @@ -5,7 +5,10 @@ use std::hint::black_box; use std::sync::Arc; -use arrow::array::{Array, ArrayRef, TimestampNanosecondArray, TimestampSecondArray}; +use arrow::array::{ + Array, ArrayRef, TimestampMicrosecondArray, TimestampMillisecondArray, + TimestampNanosecondArray, TimestampSecondArray, +}; use arrow::datatypes::Field; use criterion::{Criterion, criterion_group}; use datafusion_common::ScalarValue; @@ -31,16 +34,48 @@ fn second_timestamps() -> TimestampSecondArray { .collect() } -fn nanosecond_timestamps() -> TimestampNanosecondArray { +/// Timestamps within [`RANGE_SECONDS`] of the epoch, in units of which there +/// are `per_second` in a second. +fn timestamps(per_second: i64) -> Vec { let mut rng = seedable_rng(); (0..NUM_ROWS) .map(|_| { let seconds = rng.random_range(-RANGE_SECONDS..RANGE_SECONDS); - Some(seconds * NANOS_PER_SECOND + rng.random_range(0..NANOS_PER_SECOND)) + seconds * per_second + rng.random_range(0..per_second) }) .collect() } +/// [`timestamps`] in each time unit, in `tz`. +fn timestamps_in_each_unit(tz: Option<&str>) -> [(&'static str, ArrayRef); 4] { + [ + ( + "nanos", + Arc::new( + TimestampNanosecondArray::from(timestamps(NANOS_PER_SECOND)) + .with_timezone_opt(tz), + ), + ), + ( + "micros", + Arc::new( + TimestampMicrosecondArray::from(timestamps(1_000_000)) + .with_timezone_opt(tz), + ), + ), + ( + "millis", + Arc::new( + TimestampMillisecondArray::from(timestamps(1_000)).with_timezone_opt(tz), + ), + ), + ( + "seconds", + Arc::new(TimestampSecondArray::from(timestamps(1)).with_timezone_opt(tz)), + ), + ] +} + fn run_benchmark(c: &mut Criterion, name: &str, granularity: &str, array: ArrayRef) { let batch_len = array.len(); let precision = @@ -83,16 +118,22 @@ fn criterion_benchmark(c: &mut Criterion) { run_benchmark(c, "date_trunc_minute_1000", "minute", Arc::clone(&seconds)); run_benchmark(c, "date_trunc_month_second_1000", "month", seconds); - // Coarse granularities on an untimezoned array: these need calendar - // arithmetic rather than a plain division. - let nanos: ArrayRef = Arc::new(nanosecond_timestamps()); - for granularity in ["week", "month", "quarter", "year"] { - run_benchmark( - c, - &format!("date_trunc_{granularity}_nanos_1000"), - granularity, - Arc::clone(&nanos), - ); + // Each time unit, with and without a timezone. Without one, granularities + // from a week up need calendar arithmetic rather than a plain division; + // with one, those from an hour up are truncated in local time. + for (tz, suffix) in [(None, ""), (Some("America/New_York"), "_tz")] { + for (unit, array) in timestamps_in_each_unit(tz) { + for granularity in + ["second", "hour", "day", "week", "month", "quarter", "year"] + { + run_benchmark( + c, + &format!("date_trunc_{granularity}_{unit}{suffix}_1000"), + granularity, + Arc::clone(&array), + ); + } + } } } From 6ef9b093c377e4fb7c77555a47c1793fda05905d Mon Sep 17 00:00:00 2001 From: Cody Wyatt Neiman Date: Wed, 2 Dec 2026 15:56:39 +0000 Subject: [PATCH 2/2] fix: date_trunc truncates timestamps in their own unit at every granularity date_trunc converted second, millisecond and microsecond timestamps to nanoseconds before truncating them to an hour or a day in a timezone, or to a week, month, quarter or year. Valid timestamps before 1677-09-21 or after 2262-04-11 failed with "Timestamp ... out of range", for example the Windows FILETIME epoch, 1601-01-01, as a microsecond timestamp. Truncate in the timestamp's own unit instead. The integer path is generic over the timestamp type, so its divisors stay constants for each unit, and the timezone path converts to and from chrono in that unit. Timestamps chrono cannot represent are still rejected with the same error. At chrono's limits, a local time outside its range, or a week that starts before its first day, is an error rather than a panic. Co-Authored-By: Claude Opus 5.5 --- .../datetime_expressions/date_trunc.rs | 20 + .../functions/src/datetime/date_trunc.rs | 491 ++++++++++++++---- .../test_files/datetime/timestamps.slt | 146 ++++++ 3 files changed, 559 insertions(+), 98 deletions(-) diff --git a/datafusion/functions/benches/datetime_expressions/date_trunc.rs b/datafusion/functions/benches/datetime_expressions/date_trunc.rs index a65697c07d751..904680a872516 100644 --- a/datafusion/functions/benches/datetime_expressions/date_trunc.rs +++ b/datafusion/functions/benches/datetime_expressions/date_trunc.rs @@ -22,6 +22,8 @@ const NUM_ROWS: usize = 1000; const NANOS_PER_SECOND: i64 = 1_000_000_000; /// Roughly 30 years, so that values span many months, quarters and years. const RANGE_SECONDS: i64 = 30 * 365 * 24 * 60 * 60; +/// 400 years, a whole number of days and weeks, in microseconds. +const MICROS_400_YEARS: i64 = 146_097 * 24 * 60 * 60 * 1_000_000; fn seedable_rng() -> StdRng { StdRng::seed_from_u64(42) @@ -134,6 +136,24 @@ fn criterion_benchmark(c: &mut Criterion) { ); } } + + // Before the range of a nanosecond timestamp: around 1570 + let before_1677: ArrayRef = Arc::new( + TimestampMicrosecondArray::from_iter_values( + timestamps(1_000_000) + .into_iter() + .map(|value| value - MICROS_400_YEARS), + ) + .with_timezone_opt(tz), + ); + for granularity in ["day", "month", "year"] { + run_benchmark( + c, + &format!("date_trunc_{granularity}_micros_before_1677{suffix}_1000"), + granularity, + Arc::clone(&before_1677), + ); + } } } diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index e1cf374efb3bb..66989e7920624 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -3,7 +3,6 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use std::num::NonZeroI64; -use std::ops::{Add, Sub}; use std::str::FromStr; use std::sync::Arc; @@ -41,7 +40,7 @@ use datafusion_macros::user_doc; use chrono::{ DateTime, Datelike, Duration, LocalResult, Months, NaiveDate, NaiveDateTime, Offset, - TimeDelta, Timelike, Weekday, + TimeDelta, Timelike, Utc, Weekday, }; fn parse_granularity(value: &str) -> Result { @@ -291,7 +290,7 @@ impl ScalarUDFImpl for DateTruncFunc { } let array: PrimitiveArray = array - .try_unary(|x| general_date_trunc(T::UNIT, x, parsed_tz, granularity))? + .try_unary(|x| date_trunc_timestamp::(x, parsed_tz, granularity))? .with_timezone_opt(tz_opt.cloned()); Ok(ColumnarValue::Array(Arc::new(array))) } @@ -305,8 +304,7 @@ impl ScalarUDFImpl for DateTruncFunc { let value = match v { // Truncate in the input's own unit, as `process_array` does, so a // scalar accepts every timestamp a column accepts. - // `general_date_trunc` converts to nanoseconds first and so rejects - // values outside the nanosecond range. + // `date_trunc_timestamp` rejects those chrono cannot represent. Some(v) if truncates_in_input_unit(granularity, parsed_tz.as_ref()) => { match fine_granularity_unit(T::UNIT, granularity) { Some(unit) => { @@ -316,7 +314,7 @@ impl ScalarUDFImpl for DateTruncFunc { None => Some(*v), } } - Some(v) => Some(general_date_trunc(T::UNIT, *v, parsed_tz, granularity)?), + Some(v) => Some(date_trunc_timestamp::(*v, parsed_tz, granularity)?), None => None, }; let value = ScalarValue::new_timestamp::(value, tz_opt.cloned()); @@ -595,7 +593,6 @@ const NANOS_PER_MILLISECOND: i64 = NANOSECONDS / MILLISECONDS; const NANOS_PER_SECOND: i64 = NANOSECONDS; const NANOS_PER_MINUTE: i64 = 60 * NANOS_PER_SECOND; const NANOS_PER_HOUR: i64 = 60 * NANOS_PER_MINUTE; -const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR; const MICROS_PER_MILLISECOND: i64 = MICROSECONDS / MILLISECONDS; const MICROS_PER_SECOND: i64 = MICROSECONDS; @@ -661,10 +658,10 @@ fn truncate_time_secs(value: i32, granularity: DatePart) -> i32 { } } -fn _date_trunc_coarse(granularity: DatePart, value: Option) -> Result> -where - T: Datelike + Timelike + Sub + Copy, -{ +fn _date_trunc_coarse( + granularity: DatePart, + value: Option, +) -> Result> { let value = match granularity { DatePart::Millisecond => value, DatePart::Microsecond => value, @@ -686,8 +683,11 @@ where .and_then(|d| d.with_second(0)) .and_then(|d| d.with_minute(0)) .and_then(|d| d.with_hour(0)) - .map(|d| { - d - TimeDelta::try_seconds(60 * 60 * 24 * d.weekday() as i64).unwrap() + .and_then(|d| { + // The Monday before chrono's first day is out of its range + d.checked_sub_signed( + TimeDelta::try_seconds(60 * 60 * 24 * d.weekday() as i64).unwrap(), + ) }), DatePart::Month => value .and_then(|d| d.with_nanosecond(0)) @@ -1045,10 +1045,10 @@ fn timestamp_unit_scale(unit: TimeUnit) -> i64 { fn _date_trunc_coarse_with_tz( granularity: DatePart, + local: NaiveDateTime, value: DateTime, -) -> Result> { - let local = value.naive_local(); - let truncated = _date_trunc_coarse::(granularity, Some(local))?; +) -> Result>> { + let truncated = _date_trunc_coarse(granularity, Some(local))?; let truncated = truncated.and_then(|truncated| { match truncated.and_local_timezone(value.timezone()) { LocalResult::None => { @@ -1057,11 +1057,12 @@ fn _date_trunc_coarse_with_tz( // this can happen is with historic dates in the America/Sao_Paulo time zone. // To account for this adjust the time by a few hours, convert to local time, // and then adjust the time back. + let three_hours = TimeDelta::try_hours(3).unwrap(); truncated - .sub(TimeDelta::try_hours(3).unwrap()) + .checked_sub_signed(three_hours)? .and_local_timezone(value.timezone()) - .single() - .map(|v| v.add(TimeDelta::try_hours(3).unwrap())) + .single()? + .checked_add_signed(three_hours) } LocalResult::Single(datetime) => Some(datetime), LocalResult::Ambiguous(datetime1, datetime2) => { @@ -1077,7 +1078,7 @@ fn _date_trunc_coarse_with_tz( } } }); - Ok(truncated.and_then(|value| value.timestamp_nanos_opt())) + Ok(truncated) } // The two helpers below duplicate `chrono::NaiveDate::{from_epoch_days, @@ -1138,63 +1139,127 @@ fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { era * DAYS_PER_ERA + day_of_era - DAYS_EPOCH_SHIFT } -/// Truncates a UTC nanosecond timestamp with integer arithmetic. Truncating on -/// the calendar directly avoids converting every value to a `NaiveDateTime` and -/// rebuilding it field by field. +/// The number of `unit`s in one second. +const fn units_per_second(unit: TimeUnit) -> i64 { + match unit { + Second => 1, + Millisecond => MILLISECONDS, + Microsecond => MICROSECONDS, + Nanosecond => NANOSECONDS, + } +} + +/// The first and last timestamps in `unit` that chrono can represent: every +/// `i64` for nanoseconds, a narrower range than any of the other units. +const fn chrono_range(unit: TimeUnit) -> (i64, i64) { + let (min, max) = (DateTime::::MIN_UTC, DateTime::::MAX_UTC); + match unit { + Second => (min.timestamp(), max.timestamp()), + Millisecond => (min.timestamp_millis(), max.timestamp_millis()), + Microsecond => (min.timestamp_micros(), max.timestamp_micros()), + Nanosecond => (i64::MIN, i64::MAX), + } +} + +/// Whether chrono can represent `value`, a timestamp in `T::UNIT`. Always +/// true for nanoseconds, where the check compiles away. +fn chrono_can_represent(value: i64) -> bool { + let (min, max) = const { chrono_range(T::UNIT) }; + min <= value && value <= max +} + +/// Truncates a UTC timestamp in `T::UNIT` with integer arithmetic. Truncating +/// on the calendar directly avoids converting every value to a `NaiveDateTime` +/// and rebuilding it field by field. /// -/// Returns `None` when the truncated timestamp is no longer representable as -/// nanoseconds since the epoch, which the caller reports as an out of range -/// error. -fn _date_trunc_coarse_without_tz(granularity: DatePart, value: i64) -> Option { +/// Returns `None` when the truncated timestamp is no longer representable, +/// which the caller reports as an out of range error. +fn _date_trunc_coarse_without_tz( + granularity: DatePart, + value: i64, +) -> Option { + // Constants for each unit, so that dividing by them stays cheap + let per_second = const { units_per_second(T::UNIT) }; + let per_day = const { 24 * 60 * 60 * units_per_second(T::UNIT) }; let truncate_to = |unit: i64| value.checked_sub(value.rem_euclid(unit)); - let days = || value.div_euclid(NANOS_PER_DAY); - let nanos_from_days = |days: i64| days.checked_mul(NANOS_PER_DAY); + let days = || value.div_euclid(per_day); + let from_days = |days: i64| days.checked_mul(per_day); match granularity { - // Sub-second granularities are applied by the caller, which rescales - // the nanoseconds to the time unit of the array. + // Sub-second granularities are applied by the caller. DatePart::Millisecond | DatePart::Microsecond => Some(value), - DatePart::Second => truncate_to(NANOS_PER_SECOND), - DatePart::Minute => truncate_to(NANOS_PER_MINUTE), - DatePart::Hour => truncate_to(NANOS_PER_HOUR), - DatePart::Day => nanos_from_days(days()), + DatePart::Second => truncate_to(per_second), + DatePart::Minute => truncate_to(60 * per_second), + DatePart::Hour => truncate_to(60 * 60 * per_second), + DatePart::Day => from_days(days()), DatePart::Week => { let days = days(); // `Weekday::num_days_from_monday` for the epoch (a Thursday) is 3. - nanos_from_days(days - (days + 3).rem_euclid(7)) + from_days(days - (days + 3).rem_euclid(7)) + // The Monday before chrono's first day is out of its range + .filter(|&value| chrono_can_represent::(value)) } DatePart::Month => { let days = days(); let (_, _, day_of_month) = civil_from_days(days); - nanos_from_days(days - (day_of_month - 1)) + from_days(days - (day_of_month - 1)) } DatePart::Quarter => { let (year, month, _) = civil_from_days(days()); - nanos_from_days(days_from_civil(year, 1 + 3 * ((month - 1) / 3), 1)) + from_days(days_from_civil(year, 1 + 3 * ((month - 1) / 3), 1)) } DatePart::Year => { let (year, _, _) = civil_from_days(days()); - nanos_from_days(days_from_civil(year, 1, 1)) + from_days(days_from_civil(year, 1, 1)) } _ => unreachable!("unsupported date_trunc granularity"), } } -/// Truncates the single `value`, expressed in nanoseconds since the -/// epoch, for granularities greater than 1 second, in taking into -/// account that some granularities are not uniform durations of time -/// (e.g. months are not always the same lengths, leap seconds, etc) -fn date_trunc_coarse(granularity: DatePart, value: i64, tz: Option) -> Result { +/// `value` as a timestamp in `T::UNIT`, or `None` when it does not fit in an +/// `i64`. +fn datetime_to_timestamp(value: DateTime) -> Option { + match T::UNIT { + Second => Some(value.timestamp()), + Millisecond => Some(value.timestamp_millis()), + Microsecond => Some(value.timestamp_micros()), + Nanosecond => value.timestamp_nanos_opt(), + } +} + +/// Truncates the single `value`, a timestamp in `T::UNIT`, in that unit, for +/// granularities greater than 1 second, in taking into account that some +/// granularities are not uniform durations of time (e.g. months are not +/// always the same lengths, leap seconds, etc) +/// +/// Every timestamp chrono can represent is accepted, where converting to +/// nanoseconds first would reject those before 1677-09-21 and after +/// 2262-04-11. +fn date_trunc_coarse( + granularity: DatePart, + value: i64, + tz: Option, +) -> Result { let input = value; + let out_of_range = || exec_datafusion_err!("Timestamp {input} out of range"); let value = match tz { Some(tz) => { // Use chrono DateTime to clear the various fields because need to clear per timezone, // and NaiveDateTime (ISO 8601) has no concept of timezones - let value = as_datetime_with_timezone::(value, tz) - .ok_or(exec_datafusion_err!("Timestamp {value} out of range"))?; - _date_trunc_coarse_with_tz(granularity, value)? + let value = + as_datetime_with_timezone::(value, tz).ok_or_else(out_of_range)?; + // Not `naive_local`, which panics where the local time is out of + // chrono's range, at its limits + let local = value + .naive_utc() + .checked_add_offset(value.offset().fix()) + .ok_or_else(out_of_range)?; + _date_trunc_coarse_with_tz(granularity, local, value)? + .and_then(datetime_to_timestamp::) } - None => _date_trunc_coarse_without_tz(granularity, value), + // Accept the same timestamps as with a timezone + None if !chrono_can_represent::(value) => return Err(out_of_range()), + None => _date_trunc_coarse_without_tz::(granularity, value), }; value.ok_or_else(|| { @@ -1308,52 +1373,43 @@ fn general_date_trunc( tz: Option, granularity: DatePart, ) -> Result { - let scale = match tu { - Second => 1_000_000_000, - Millisecond => 1_000_000, - Microsecond => 1_000, - Nanosecond => 1, - }; + match tu { + Second => date_trunc_timestamp::(value, tz, granularity), + Millisecond => { + date_trunc_timestamp::(value, tz, granularity) + } + Microsecond => { + date_trunc_timestamp::(value, tz, granularity) + } + Nanosecond => { + date_trunc_timestamp::(value, tz, granularity) + } + } +} - // convert to nanoseconds - let nano = date_trunc_coarse( - granularity, - value - .checked_mul(scale) - .ok_or_else(|| exec_datafusion_err!("Timestamp {value} out of range"))?, - tz, - )?; - - let truncate_to = |value: i64, unit: i64| { - value - .checked_sub(value.rem_euclid(unit)) - .ok_or_else(|| exec_datafusion_err!("Timestamp {value} out of range")) - }; - let result = match tu { - Second => match granularity { - DatePart::Minute => nano / 1_000_000_000 / 60 * 60, - _ => nano / 1_000_000_000, - }, - Millisecond => match granularity { - DatePart::Minute => nano / 1_000_000 / 1_000 / 60 * 1_000 * 60, - DatePart::Second => nano / 1_000_000 / 1_000 * 1_000, - _ => nano / 1_000_000, - }, - Microsecond => match granularity { - DatePart::Minute => nano / 1_000 / 1_000_000 / 60 * 60 * 1_000_000, - DatePart::Second => nano / 1_000 / 1_000_000 * 1_000_000, - DatePart::Millisecond => truncate_to(nano / 1_000, 1_000)?, - _ => nano / 1_000, - }, - _ => match granularity { - DatePart::Minute => nano / 1_000_000_000 / 60 * 1_000_000_000 * 60, - DatePart::Second => nano / 1_000_000_000 * 1_000_000_000, - DatePart::Millisecond => truncate_to(nano, 1_000_000)?, - DatePart::Microsecond => truncate_to(nano, 1_000)?, - _ => nano, - }, +/// [`general_date_trunc`] for a timestamp in `T::UNIT`, truncated in that unit. +fn date_trunc_timestamp( + value: i64, + tz: Option, + granularity: DatePart, +) -> Result { + let truncated = date_trunc_coarse::(granularity, value, tz)?; + if !granularity.is_fine_granularity() { + return Ok(truncated); + } + let Some(unit) = fine_granularity_unit(T::UNIT, granularity) else { + return Ok(truncated); }; - Ok(result) + let unit = unit.get(); + match granularity { + // With a timezone, `date_trunc_coarse` truncates to the second or + // minute in local time. Truncating toward zero in UTC as well, as + // before, only matters where the offset is not a whole number of + // minutes. + DatePart::Second | DatePart::Minute => Ok(truncated / unit * unit), + // `date_trunc_coarse` leaves sub-second granularities to us + _ => truncate_to_unit(truncated, unit, granularity), + } } #[cfg(test)] @@ -1361,11 +1417,13 @@ mod tests { use std::sync::Arc; use crate::datetime::date_trunc::{ - DateTruncFunc, NANOS_PER_MICROSECOND, date_trunc_coarse, general_date_trunc, - general_date_trunc_array_fine_granularity, parse_granularity, + DateTruncFunc, NANOS_PER_MICROSECOND, chrono_range, date_trunc_coarse, + general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, }; use arrow::array::cast::as_primitive_array; + use arrow::array::temporal_conversions::NANOSECONDS; + use arrow::array::timezone::Tz; use arrow::array::types::{ ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType, @@ -1679,7 +1737,12 @@ mod tests { let left = string_to_timestamp_nanos(original).unwrap(); let right = string_to_timestamp_nanos(expected).unwrap(); let granularity_enum = parse_granularity(granularity).unwrap(); - let result = date_trunc_coarse(granularity_enum, left, None).unwrap(); + let result = date_trunc_coarse::( + granularity_enum, + left, + None, + ) + .unwrap(); assert_eq!(result, right, "{original} = {expected}"); } } @@ -1687,9 +1750,10 @@ mod tests { #[test] fn date_trunc_out_of_range_lower_bound_returns_error() { let timestamp = string_to_timestamp_nanos("1677-09-22T00:00:00Z").unwrap(); - let err = date_trunc_coarse(DatePart::Year, timestamp, None) - .unwrap_err() - .to_string(); + let err = + date_trunc_coarse::(DatePart::Year, timestamp, None) + .unwrap_err() + .to_string(); assert!( err.contains("out of range after truncating to year"), @@ -2461,4 +2525,235 @@ mod tests { } } } + + const GRANULARITIES: [DatePart; 10] = [ + DatePart::Microsecond, + DatePart::Millisecond, + DatePart::Second, + DatePart::Minute, + DatePart::Hour, + DatePart::Day, + DatePart::Week, + DatePart::Month, + DatePart::Quarter, + DatePart::Year, + ]; + + const UNITS: [TimeUnit; 4] = [ + TimeUnit::Second, + TimeUnit::Millisecond, + TimeUnit::Microsecond, + TimeUnit::Nanosecond, + ]; + + fn timezones(names: &[&str]) -> Vec> { + let timezones = names.iter().map(|name| Some(name.parse().unwrap())); + std::iter::once(None).chain(timezones).collect() + } + + /// `count` values spread over `min..=max`, and the values at either end + fn values_between(min: i64, max: i64, count: usize) -> Vec { + let width = i128::from(max) - i128::from(min) + 1; + let mut state: u64 = 42; + let mut values = vec![min, min + 1, max - 1, max]; + values.extend((0..count).map(|_| { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (i128::from(min) + i128::from(state) % width) as i64 + })); + values + } + + #[test] + fn date_trunc_in_unit_matches_nanoseconds() { + // Within the range of a nanosecond timestamp, truncating a timestamp in + // its own unit gives what converting it to nanoseconds first did. + let max_seconds = i64::MAX / NANOSECONDS; + let mut seconds = values_between(-max_seconds, max_seconds, 300); + // Around DST transitions in New York, Sao Paulo, Lord Howe and Berlin + for transition in [ + 1_710_054_000, + 1_730_613_600, + 1_541_300_400, + 1_728_142_200, + 1_712_415_600, + 1_711_846_800, + 1_729_990_800, + ] { + for offset in [-3_601, -1_800, -1, 0, 1, 1_800, 3_599] { + seconds.push(transition + offset); + } + } + let timezones = timezones(&[ + "UTC", + "+05:30", + "-03:00", + "America/New_York", + "America/Sao_Paulo", + "Australia/Lord_Howe", + "Asia/Kathmandu", + "Europe/Berlin", + ]); + + for (unit, per_second) in [ + (TimeUnit::Second, 1), + (TimeUnit::Millisecond, 1_000), + (TimeUnit::Microsecond, 1_000_000), + ] { + let scale = NANOSECONDS / per_second; + for &seconds in &seconds { + let value = seconds * per_second + seconds.rem_euclid(per_second); + let Some(nanos) = value.checked_mul(scale) else { + continue; + }; + for &tz in &timezones { + for granularity in GRANULARITIES { + let actual = general_date_trunc(unit, value, tz, granularity) + .unwrap_or_else(|e| { + panic!("{unit} {value} {tz:?} {granularity}: {e}") + }); + // Truncating to nanoseconds fails where the result + // falls before 1677-09-21 + let Ok(expected) = general_date_trunc( + TimeUnit::Nanosecond, + nanos, + tz, + granularity, + ) else { + continue; + }; + assert_eq!( + actual, + expected / scale, + "{unit} {value} {tz:?} {granularity}" + ); + } + } + } + } + } + + #[test] + fn date_trunc_without_timezone_matches_utc() { + // Without a timezone, integer arithmetic truncates as chrono does in + // UTC, over the whole of chrono's range in every unit. + let utc = Some("UTC".parse().unwrap()); + for unit in UNITS { + let (min, max) = chrono_range(unit); + for value in values_between(min, max, 2_000) { + for granularity in GRANULARITIES { + let without_tz = general_date_trunc(unit, value, None, granularity); + let in_utc = general_date_trunc(unit, value, utc, granularity); + assert_eq!( + without_tz.as_ref().ok(), + in_utc.as_ref().ok(), + "{unit} {value} {granularity}: {without_tz:?} {in_utc:?}" + ); + } + } + } + } + + #[test] + fn date_trunc_at_the_limits() { + let timezones = timezones(&[ + "UTC", + "+05:00", + "-05:00", + "America/New_York", + "Asia/Kathmandu", + ]); + for unit in UNITS { + let (min, max) = chrono_range(unit); + let values = [ + i64::MIN, + i64::MIN + 1, + min.saturating_sub(1), + min, + min + 1, + -1, + 0, + 1, + max - 1, + max, + max.saturating_add(1), + i64::MAX - 1, + i64::MAX, + ]; + for value in values { + for &tz in &timezones { + for granularity in GRANULARITIES { + let context = format!("{unit} {value} {tz:?} {granularity}"); + match general_date_trunc(unit, value, tz, granularity) { + Ok(truncated) => { + assert!((min..=max).contains(&value), "{context}"); + assert!((min..=max).contains(&truncated), "{context}"); + assert!(truncated <= value, "{context}"); + } + // Rejected as before when chrono can not represent + // the timestamp + Err(e) if !(min..=max).contains(&value) => { + let e = e.to_string(); + assert!( + e.contains(&format!( + "Timestamp {value} out of range" + )) && !e.contains("after truncating"), + "{context}: {e}" + ); + } + Err(e) => assert!( + e.to_string().contains("out of range"), + "{context}: {e}" + ), + } + } + } + } + } + } + + #[test] + fn date_trunc_beyond_nanoseconds() { + let utc = Some("UTC".parse().unwrap()); + let ahead = Some("+05:00".parse().unwrap()); + let (min, max) = chrono_range(TimeUnit::Second); + let truncate = |value, tz, granularity| { + general_date_trunc(TimeUnit::Second, value, tz, granularity) + .map_err(|e| e.to_string()) + }; + + // 1601-03-15T13:42:29Z, before the range of a nanosecond timestamp + let value = -11_638_117_051; + assert_eq!(truncate(value, ahead, DatePart::Hour), Ok(-11_638_119_600)); + for (granularity, expected) in [ + (DatePart::Hour, -11_638_119_600), + (DatePart::Day, -11_638_166_400), + (DatePart::Week, -11_638_425_600), + (DatePart::Month, -11_639_376_000), + (DatePart::Quarter, -11_644_473_600), + (DatePart::Year, -11_644_473_600), + ] { + assert_eq!(truncate(value, None, granularity), Ok(expected)); + assert_eq!(truncate(value, utc, granularity), Ok(expected)); + if granularity != DatePart::Hour { + assert_eq!( + truncate(value, ahead, granularity), + Ok(expected - 5 * 3_600) + ); + } + } + + // chrono's first day is a Thursday, so its week starts out of range + assert_eq!(truncate(min, None, DatePart::Month), Ok(min)); + assert_eq!(truncate(min, utc, DatePart::Year), Ok(min)); + for tz in [None, utc] { + let e = truncate(min + 3_600, tz, DatePart::Week).unwrap_err(); + assert!(e.contains("out of range after truncating to week"), "{e}"); + } + // Local times past chrono's last day are out of its range + assert_eq!(truncate(max, utc, DatePart::Day), Ok(max - 86_399)); + let e = truncate(max, ahead, DatePart::Day).unwrap_err(); + assert!(e.contains(&format!("Timestamp {max} out of range")), "{e}"); + } } diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt index 01ed3a9edc881..ec9b9543dfc52 100644 --- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt +++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt @@ -3177,6 +3177,152 @@ SELECT date_trunc( arrow_cast(9223372036854775807, 'Timestamp(Second, None)') ); +# date_trunc truncates a timestamp in its own unit to any granularity, with or +# without a timezone, including timestamps beyond the range of a nanosecond +# timestamp (1601-01-01 is the Windows FILETIME epoch) +statement ok +CREATE TABLE wide_timestamps AS +SELECT + arrow_cast(column1, 'Timestamp(µs)') AS us, + arrow_cast(column1, 'Timestamp(µs, "UTC")') AS us_utc, + arrow_cast(column1, 'Timestamp(µs, "Europe/Berlin")') AS us_berlin, + arrow_cast(column1 / 1000, 'Timestamp(ms)') AS ms, + arrow_cast(column1 / 1000, 'Timestamp(ms, "UTC")') AS ms_utc, + arrow_cast(column1 / 1000, 'Timestamp(ms, "America/New_York")') AS ms_new_york, + arrow_cast(column1 / 1000000, 'Timestamp(s)') AS s, + arrow_cast(column1 / 1000000, 'Timestamp(s, "+05:00")') AS s_ahead +FROM (VALUES + (-11638116869876544), + (1700000000000001), + (9223376523000004), + (253402300799999999) +); + +query PPPPP +SELECT + date_trunc('hour', us), + date_trunc('day', us), + date_trunc('week', us), + date_trunc('month', us), + date_trunc('year', us) +FROM wide_timestamps ORDER BY us; +---- +1601-03-15T13:00:00 1601-03-15T00:00:00 1601-03-12T00:00:00 1601-03-01T00:00:00 1601-01-01T00:00:00 +2023-11-14T22:00:00 2023-11-14T00:00:00 2023-11-13T00:00:00 2023-11-01T00:00:00 2023-01-01T00:00:00 +2262-04-12T01:00:00 2262-04-12T00:00:00 2262-04-07T00:00:00 2262-04-01T00:00:00 2262-01-01T00:00:00 +9999-12-31T23:00:00 9999-12-31T00:00:00 9999-12-27T00:00:00 9999-12-01T00:00:00 9999-01-01T00:00:00 + +query PPPPP +SELECT + date_trunc('hour', us_utc), + date_trunc('day', us_utc), + date_trunc('week', us_utc), + date_trunc('quarter', us_utc), + date_trunc('year', us_utc) +FROM wide_timestamps ORDER BY us; +---- +1601-03-15T13:00:00Z 1601-03-15T00:00:00Z 1601-03-12T00:00:00Z 1601-01-01T00:00:00Z 1601-01-01T00:00:00Z +2023-11-14T22:00:00Z 2023-11-14T00:00:00Z 2023-11-13T00:00:00Z 2023-10-01T00:00:00Z 2023-01-01T00:00:00Z +2262-04-12T01:00:00Z 2262-04-12T00:00:00Z 2262-04-07T00:00:00Z 2262-04-01T00:00:00Z 2262-01-01T00:00:00Z +9999-12-31T23:00:00Z 9999-12-31T00:00:00Z 9999-12-27T00:00:00Z 9999-10-01T00:00:00Z 9999-01-01T00:00:00Z + +query PPPP +SELECT + date_trunc('hour', us_berlin), + date_trunc('day', us_berlin), + date_trunc('month', us_berlin), + date_trunc('year', us_berlin) +FROM wide_timestamps ORDER BY us; +---- +1601-03-15T13:06:32Z 1601-03-14T23:06:32Z 1601-02-28T23:06:32Z 1600-12-31T23:06:32Z +2023-11-14T23:00:00+01:00 2023-11-14T00:00:00+01:00 2023-11-01T00:00:00+01:00 2023-01-01T00:00:00+01:00 +2262-04-12T02:00:00+01:00 2262-04-12T00:00:00+01:00 2262-04-01T00:00:00+01:00 2262-01-01T00:00:00+01:00 ++10000-01-01T00:00:00+01:00 +10000-01-01T00:00:00+01:00 +10000-01-01T00:00:00+01:00 +10000-01-01T00:00:00+01:00 + +query PPPP +SELECT + date_trunc('hour', ms_utc), + date_trunc('day', ms_utc), + date_trunc('month', s), + date_trunc('year', s) +FROM wide_timestamps ORDER BY us; +---- +1601-03-15T13:00:00Z 1601-03-15T00:00:00Z 1601-03-01T00:00:00 1601-01-01T00:00:00 +2023-11-14T22:00:00Z 2023-11-14T00:00:00Z 2023-11-01T00:00:00 2023-01-01T00:00:00 +2262-04-12T01:00:00Z 2262-04-12T00:00:00Z 2262-04-01T00:00:00 2262-01-01T00:00:00 +9999-12-31T23:00:00Z 9999-12-31T00:00:00Z 9999-12-01T00:00:00 9999-01-01T00:00:00 + +# the same as scalars +query PPP +SELECT + date_trunc('day', arrow_cast(-11638116869876544, 'Timestamp(µs, "UTC")')), + date_trunc('month', arrow_cast(-11638116869876544, 'Timestamp(µs, "Europe/Berlin")')), + date_trunc('year', arrow_cast(253402300799999999, 'Timestamp(µs)')); +---- +1601-03-15T00:00:00Z 1601-02-28T23:06:32Z 9999-01-01T00:00:00 + +# the remaining units and granularities, without a timezone and in one +query PPPPPP +SELECT + date_trunc('week', ms), + date_trunc('quarter', ms), + date_trunc('quarter', s), + date_trunc('hour', s_ahead), + date_trunc('week', s_ahead), + date_trunc('quarter', ms_new_york) +FROM wide_timestamps ORDER BY us; +---- +1601-03-12T00:00:00 1601-01-01T00:00:00 1601-01-01T00:00:00 1601-03-15T18:00:00+05:00 1601-03-12T00:00:00+05:00 1601-01-01T04:56:02Z +2023-11-13T00:00:00 2023-10-01T00:00:00 2023-10-01T00:00:00 2023-11-15T03:00:00+05:00 2023-11-13T00:00:00+05:00 2023-10-01T00:00:00-04:00 +2262-04-07T00:00:00 2262-04-01T00:00:00 2262-04-01T00:00:00 2262-04-12T06:00:00+05:00 2262-04-07T00:00:00+05:00 2262-04-01T00:00:00-05:00 +9999-12-27T00:00:00 9999-10-01T00:00:00 9999-10-01T00:00:00 +10000-01-01T04:00:00+05:00 9999-12-27T00:00:00+05:00 9999-10-01T00:00:00-05:00 + +statement ok +DROP TABLE wide_timestamps; + +# date_trunc keeps the DST offset of the input, in every unit +query PPP +SELECT + date_trunc('hour', arrow_cast(column1, 'Timestamp(µs, "America/New_York")')), + date_trunc('hour', arrow_cast(column1 / 1000, 'Timestamp(ms, "America/New_York")')), + date_trunc('day', arrow_cast(column1 / 1000000, 'Timestamp(s, "America/New_York")')) +FROM (VALUES (1730611800123456), (1730615400123456)); +---- +2024-11-03T01:00:00-04:00 2024-11-03T01:00:00-04:00 2024-11-03T00:00:00-04:00 +2024-11-03T01:00:00-05:00 2024-11-03T01:00:00-05:00 2024-11-03T00:00:00-04:00 + +# date_trunc accepts every timestamp chrono can represent, from +# -262143-01-01T00:00:00 to +262142-12-31T23:59:59.999999999 +query PPPP +SELECT + date_trunc('year', arrow_cast(-8334601228800, 'Timestamp(s)')), + date_trunc('month', arrow_cast(-8334601228800000000, 'Timestamp(µs, "UTC")')), + date_trunc('year', arrow_cast(8210266876799999, 'Timestamp(ms)')), + date_trunc('day', arrow_cast(8210266876799999999, 'Timestamp(µs, "-05:00")')); +---- +-262143-01-01T00:00:00 -262143-01-01T00:00:00Z +262142-01-01T00:00:00 +262142-12-31T00:00:00-05:00 + +# and rejects the others, as before +query error DataFusion error: Execution error: Timestamp \-8334601228801 out of range +SELECT date_trunc('year', arrow_cast(-8334601228801, 'Timestamp(s)')); + +query error DataFusion error: Execution error: Timestamp 8210266876800000 out of range +SELECT date_trunc('month', arrow_cast(8210266876800000, 'Timestamp(ms, "UTC")')); + +query error DataFusion error: Execution error: Timestamp \-9223372036854775808 out of range +SELECT date_trunc('day', arrow_cast(-9223372036854775808, 'Timestamp(µs, "UTC")')); + +# including those whose local time chrono can not represent +query error DataFusion error: Execution error: Timestamp 8210266876799 out of range +SELECT date_trunc('day', arrow_cast(8210266876799, 'Timestamp(s, "+05:00")')); + +# and week starts before chrono's first day, a Thursday +query error DataFusion error: Execution error: Timestamp \-8334601228800 out of range after truncating to week +SELECT date_trunc('week', arrow_cast(-8334601228800, 'Timestamp(s)')); + +query error DataFusion error: Execution error: Timestamp \-8334601228800000 out of range after truncating to week +SELECT date_trunc('week', arrow_cast(-8334601228800000, 'Timestamp(ms, "UTC")')); + # Error for granularities not valid for Time types query error date_trunc does not support 'day' granularity for Time types SELECT date_trunc('day', TIME '14:30:45');