This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11632-f0e855f02ffe3c09ebe051558c21a5b52f7648e6 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 534da94754aae712849ce46e6dc06f9eedf39979 Author: ump45nose <[email protected]> AuthorDate: Sun Oct 18 09:36:23 2026 +0000 fix(arrow-cast): truncate Timestamp to Date64 casts to whole days (#11632) # Which issue does this PR close? - Closes #11592. # Rationale for this change `Timestamp -> Date64` kept the time of day, so the result could hold values that are not multiples of `86_400_000`, which the `Date64` docs say are invalid. `Timestamp -> Date32` already truncates to the date, so the two casts disagreed. # What changes are included in this PR? The four `Timestamp -> Date64` arms now go through a new `timestamp_to_date64` helper next to `timestamp_to_date32`, using the same rules: - Without a timezone, the value is floored to the start of its UTC day, so timestamps before the epoch land on the previous day. Flooring `i64::MIN` milliseconds to a day overflows, so that case is null for a safe cast and an error otherwise, the same as the existing seconds overflow. - With a timezone, the result is the local date, which answers the question @mbutrovich raised on the issue: for `-05:00`, `1970-01-01T00:00:01Z` becomes `1969-12-31`. In other words, `cast(ts, Date64)` now equals `cast(cast(ts, Date32), Date64)`. I went with this because it matches `Date32`; if you'd prefer flooring the UTC value for zoned timestamps instead, that's an easy change. # Are these changes tested? Yes. `test_cast_timestamp_to_date64` now expects whole days, and a new `test_cast_timestamp_to_date64_whole_days` covers all four units (including a timestamp just before the epoch), the timezone case checked against the `Date32` path, and the overflow case. # Are there any significant user-facing changes? Yes, the cast returns different values than before: any `Timestamp -> Date64` cast that used to keep a time of day now returns midnight, and zoned timestamps return the local date. Values that were outside chrono's date range in a zoned array now become null (or an error for a non-safe cast), as they already do for `Date32`. AI disclosure: I used an AI coding assistant to write the change, tests, and this description. I reviewed the diff and the test expectations. Co-authored-by: ump45nose <[email protected]> --- arrow-cast/src/cast/mod.rs | 96 +++++++++++++++++++++++++++++------------ arrow-cast/src/cast/temporal.rs | 49 +++++++++++++++++++++ 2 files changed, 117 insertions(+), 28 deletions(-) diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs index bfebdcdfe7..25fbf0680b 100644 --- a/arrow-cast/src/cast/mod.rs +++ b/arrow-cast/src/cast/mod.rs @@ -1947,30 +1947,21 @@ pub fn cast_with_options( array.as_primitive::<TimestampNanosecondType>(), cast_options, ), - (Timestamp(TimeUnit::Second, _), Date64) => Ok(Arc::new(match cast_options.safe { - true => { - // change error to None - array - .as_primitive::<TimestampSecondType>() - .unary_opt::<_, Date64Type>(|x| x.checked_mul(MILLISECONDS)) - } - false => array - .as_primitive::<TimestampSecondType>() - .try_unary::<_, Date64Type, _>(|x| x.mul_checked(MILLISECONDS))?, - })), - (Timestamp(TimeUnit::Millisecond, _), Date64) => { - cast_reinterpret_arrays::<TimestampMillisecondType, Date64Type>(array) - } - (Timestamp(TimeUnit::Microsecond, _), Date64) => Ok(Arc::new( - array - .as_primitive::<TimestampMicrosecondType>() - .unary::<_, Date64Type>(|x| x / (MICROSECONDS / MILLISECONDS)), - )), - (Timestamp(TimeUnit::Nanosecond, _), Date64) => Ok(Arc::new( - array - .as_primitive::<TimestampNanosecondType>() - .unary::<_, Date64Type>(|x| x / (NANOSECONDS / MILLISECONDS)), - )), + (Timestamp(TimeUnit::Second, _), Date64) => { + timestamp_to_date64(array.as_primitive::<TimestampSecondType>(), cast_options) + } + (Timestamp(TimeUnit::Millisecond, _), Date64) => timestamp_to_date64( + array.as_primitive::<TimestampMillisecondType>(), + cast_options, + ), + (Timestamp(TimeUnit::Microsecond, _), Date64) => timestamp_to_date64( + array.as_primitive::<TimestampMicrosecondType>(), + cast_options, + ), + (Timestamp(TimeUnit::Nanosecond, _), Date64) => timestamp_to_date64( + array.as_primitive::<TimestampNanosecondType>(), + cast_options, + ), (Timestamp(TimeUnit::Second, _), Time32(_) | Time64(_)) => { cast_timestamp_to_time::<TimestampSecondType>(array, to_type, cast_options) } @@ -5713,15 +5704,15 @@ mod tests { TimestampMillisecondArray::from(vec![Some(864000000005), Some(1545696000001), None]); let b = cast(&array, &DataType::Date64).unwrap(); let c = b.as_primitive::<Date64Type>(); - assert_eq!(864000000005, c.value(0)); - assert_eq!(1545696000001, c.value(1)); + assert_eq!(864000000000, c.value(0)); + assert_eq!(1545696000000, c.value(1)); assert!(c.is_null(2)); let array = TimestampSecondArray::from(vec![Some(864000000005), Some(1545696000001)]); let b = cast(&array, &DataType::Date64).unwrap(); let c = b.as_primitive::<Date64Type>(); - assert_eq!(864000000005000, c.value(0)); - assert_eq!(1545696000001000, c.value(1)); + assert_eq!(864000000000000, c.value(0)); + assert_eq!(1545696000000000, c.value(1)); // test overflow, safe cast let array = TimestampSecondArray::from(vec![Some(i64::MAX)]); @@ -5737,6 +5728,55 @@ mod tests { assert!(b.is_err()); } + #[test] + fn test_cast_timestamp_to_date64_whole_days() { + // 2024-05-01T10:30:00, 1970-01-01T00:00:00, and one millisecond before the epoch + let millis: [i64; 3] = [1_714_559_400_000, 0, -1]; + let expected = Date64Array::from(vec![1_714_521_600_000, 0, -MILLISECONDS_IN_DAY]); + let arrays: [ArrayRef; 4] = [ + Arc::new(TimestampSecondArray::from( + millis.map(|x| x.div_euclid(1_000)).to_vec(), + )), + Arc::new(TimestampMillisecondArray::from(millis.to_vec())), + Arc::new(TimestampMicrosecondArray::from( + millis.map(|x| x * 1_000).to_vec(), + )), + Arc::new(TimestampNanosecondArray::from( + millis.map(|x| x * 1_000_000).to_vec(), + )), + ]; + for array in arrays { + let actual = cast(&array, &DataType::Date64).unwrap(); + let actual = actual.as_primitive::<Date64Type>(); + // The second timestamp array rounds -1ms down to -1s, which is still the + // day before the epoch. + assert_eq!(actual, &expected, "{}", array.data_type()); + } + + // With a timezone the date is the local date, as for Date32. + // 1970-01-01T00:00:01Z and 1970-01-01T20:00:00Z are 1969-12-31 and 1970-01-01 in -05:00. + let array = TimestampSecondArray::from(vec![1, 72_000]).with_timezone("-05:00"); + let date64 = cast(&array, &DataType::Date64).unwrap(); + assert_eq!( + date64.as_primitive::<Date64Type>(), + &Date64Array::from(vec![-MILLISECONDS_IN_DAY, 0]) + ); + let date32 = cast(&array, &DataType::Date32).unwrap(); + assert_eq!( + cast(&date32, &DataType::Date64).unwrap().as_ref(), + date64.as_ref() + ); + + // Flooring i64::MIN milliseconds to a whole day overflows. + let array = TimestampMillisecondArray::from(vec![i64::MIN]); + assert!(cast(&array, &DataType::Date64).unwrap().is_null(0)); + let options = CastOptions { + safe: false, + ..Default::default() + }; + assert!(cast_with_options(&array, &DataType::Date64, &options).is_err()); + } + #[test] fn test_cast_timestamp_to_time64() { // test timestamp secs diff --git a/arrow-cast/src/cast/temporal.rs b/arrow-cast/src/cast/temporal.rs index 4d5a0cac98..66a3351229 100644 --- a/arrow-cast/src/cast/temporal.rs +++ b/arrow-cast/src/cast/temporal.rs @@ -355,6 +355,55 @@ pub(crate) fn timestamp_to_date32<T: ArrowTimestampType>( Ok(Arc::new(array)) } +/// Casts a timestamp array to `Date64`. +/// +/// `Date64` values must be whole days, so this truncates to the start of the +/// day the same way [`timestamp_to_date32`] does: in the array's timezone when it +/// has one, otherwise rounding down so that a timestamp just before the epoch +/// belongs to the preceding day. +pub(crate) fn timestamp_to_date64<T: ArrowTimestampType>( + array: &PrimitiveArray<T>, + cast_options: &CastOptions, +) -> Result<ArrayRef, ArrowError> { + let err = |x: i64| { + ArrowError::CastError(format!( + "Cannot convert {} {x} to Date64", + std::any::type_name::<T>() + )) + }; + + let array: Date64Array = match array.timezone() { + Some(tz) => { + let tz: Tz = tz.parse()?; + // Chrono's date range is small enough that the product cannot overflow. + let date = |x: i64| { + as_datetime_with_timezone::<T>(x, tz).map(|d| { + Date32Type::from_naive_date(d.date_naive()) as i64 * MILLISECONDS_IN_DAY + }) + }; + if cast_options.safe { + array.unary_opt(date) + } else { + array.try_unary(|x| date(x).ok_or_else(|| err(x)))? + } + } + None => { + // Rescaling whole days to milliseconds can overflow for second and + // millisecond timestamps near the ends of the i64 range. + let date = |x: i64| { + x.div_euclid(units_per_day::<T>()) + .checked_mul(MILLISECONDS_IN_DAY) + }; + if cast_options.safe { + array.unary_opt(date) + } else { + array.try_unary(|x| date(x).ok_or_else(|| err(x)))? + } + } + }; + Ok(Arc::new(array)) +} + /// Returns the offset to use when interpreting `local` as a wall clock reading /// in `tz`, or `None` if it cannot be resolved. ///
