Skip to content

Commit 5edda9b

Browse files
authored
fix: calculate total seconds from interval fields for extract(epoch) (#19807)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #19799. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> The epoch function incorrectly used `date_part(array, DatePart::Second)` for intervals which only extracts the seconds component of the interval structure (0 for "15 minutes"), not the total seconds from all components. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> - Modified epoch() function in date_part.rs to properly handle interval types by extracting struct fields and calculating total seconds - Added regression tests in date_part.slt ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes. Added tests verifying correct conversion for all interval types and precision levels. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> Yes. `extract(epoch from interval)` now returns correct total seconds instead of 0. <!-- If there are any breaking changes to public APIs, please add the `api change` label. -->
1 parent 444ddf2 commit 5edda9b

3 files changed

Lines changed: 77 additions & 6 deletions

File tree

datafusion/functions/src/datetime/date_part.rs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,16 @@ use arrow::datatypes::DataType::{
2626
Date32, Date64, Duration, Interval, Time32, Time64, Timestamp,
2727
};
2828
use arrow::datatypes::TimeUnit::{Microsecond, Millisecond, Nanosecond, Second};
29-
use arrow::datatypes::{DataType, Field, FieldRef, TimeUnit};
29+
use arrow::datatypes::{
30+
DataType, Field, FieldRef, IntervalUnit as ArrowIntervalUnit, TimeUnit,
31+
};
3032
use datafusion_common::types::{NativeType, logical_date};
3133

3234
use datafusion_common::{
3335
Result, ScalarValue,
3436
cast::{
35-
as_date32_array, as_date64_array, as_int32_array, as_time32_millisecond_array,
37+
as_date32_array, as_date64_array, as_int32_array, as_interval_dt_array,
38+
as_interval_mdn_array, as_interval_ym_array, as_time32_millisecond_array,
3639
as_time32_second_array, as_time64_microsecond_array, as_time64_nanosecond_array,
3740
as_timestamp_microsecond_array, as_timestamp_millisecond_array,
3841
as_timestamp_nanosecond_array, as_timestamp_second_array,
@@ -56,7 +59,7 @@ use datafusion_macros::user_doc;
5659
argument(
5760
name = "part",
5861
description = r#"Part of the date to return. The following date parts are supported:
59-
62+
6063
- year
6164
- quarter (emits value in inclusive range [1, 4] based on which quartile of the year the date is in)
6265
- month
@@ -70,7 +73,7 @@ use datafusion_macros::user_doc;
7073
- nanosecond
7174
- dow (day of the week where Sunday is 0)
7275
- doy (day of the year)
73-
- epoch (seconds since Unix epoch)
76+
- epoch (seconds since Unix epoch for timestamps/dates, total seconds for intervals)
7477
- isodow (day of the week where Monday is 0)
7578
"#
7679
),
@@ -349,6 +352,11 @@ fn seconds(array: &dyn Array, unit: TimeUnit) -> Result<ArrayRef> {
349352

350353
fn epoch(array: &dyn Array) -> Result<ArrayRef> {
351354
const SECONDS_IN_A_DAY: f64 = 86400_f64;
355+
// Note: Month-to-second conversion uses 30 days as an approximation.
356+
// This matches PostgreSQL's behavior for interval epoch extraction,
357+
// but does not represent exact calendar months (which vary 28-31 days).
358+
// See: https://doxygen.postgresql.org/datatype_2timestamp_8h.html
359+
const DAYS_PER_MONTH: f64 = 30_f64;
352360

353361
let f: Float64Array = match array.data_type() {
354362
Timestamp(Second, _) => as_timestamp_second_array(array)?.unary(|x| x as f64),
@@ -373,7 +381,19 @@ fn epoch(array: &dyn Array) -> Result<ArrayRef> {
373381
Time64(Nanosecond) => {
374382
as_time64_nanosecond_array(array)?.unary(|x| x as f64 / 1_000_000_000_f64)
375383
}
376-
Interval(_) | Duration(_) => return seconds(array, Second),
384+
Interval(ArrowIntervalUnit::YearMonth) => as_interval_ym_array(array)?
385+
.unary(|x| x as f64 * DAYS_PER_MONTH * SECONDS_IN_A_DAY),
386+
Interval(ArrowIntervalUnit::DayTime) => as_interval_dt_array(array)?.unary(|x| {
387+
x.days as f64 * SECONDS_IN_A_DAY + x.milliseconds as f64 / 1_000_f64
388+
}),
389+
Interval(ArrowIntervalUnit::MonthDayNano) => {
390+
as_interval_mdn_array(array)?.unary(|x| {
391+
x.months as f64 * DAYS_PER_MONTH * SECONDS_IN_A_DAY
392+
+ x.days as f64 * SECONDS_IN_A_DAY
393+
+ x.nanoseconds as f64 / 1_000_000_000_f64
394+
})
395+
}
396+
Duration(_) => return seconds(array, Second),
377397
d => return exec_err!("Cannot convert {d:?} to epoch"),
378398
};
379399
Ok(Arc::new(f))

datafusion/sqllogictest/test_files/datetime/date_part.slt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,57 @@ SELECT extract(second from arrow_cast(NULL, 'Interval(MonthDayNano)'))
936936
----
937937
NULL
938938

939+
# extract epoch from intervals
940+
query R
941+
SELECT extract(epoch from interval '15 minutes')
942+
----
943+
900
944+
945+
query R
946+
SELECT extract(epoch from interval '1 hour')
947+
----
948+
3600
949+
950+
query R
951+
SELECT extract(epoch from interval '1 day')
952+
----
953+
86400
954+
955+
query R
956+
SELECT extract(epoch from interval '1 month')
957+
----
958+
2592000
959+
960+
query R
961+
SELECT extract(epoch from arrow_cast('3 days', 'Interval(DayTime)'))
962+
----
963+
259200
964+
965+
query R
966+
SELECT extract(epoch from arrow_cast('100 milliseconds', 'Interval(MonthDayNano)'))
967+
----
968+
0.1
969+
970+
query R
971+
SELECT extract(epoch from arrow_cast('500 microseconds', 'Interval(MonthDayNano)'))
972+
----
973+
0.0005
974+
975+
query R
976+
SELECT extract(epoch from arrow_cast('2500 nanoseconds', 'Interval(MonthDayNano)'))
977+
----
978+
0.0000025
979+
980+
query R
981+
SELECT extract(epoch from arrow_cast('1 month 2 days 500 milliseconds', 'Interval(MonthDayNano)'))
982+
----
983+
2764800.5
984+
985+
query R
986+
SELECT extract(epoch from arrow_cast('2 months', 'Interval(YearMonth)'))
987+
----
988+
5184000
989+
939990
statement ok
940991
create table t (id int, i interval) as values
941992
(0, interval '5 months 1 day 10 nanoseconds'),

docs/source/user-guide/sql/scalar_functions.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2531,7 +2531,7 @@ date_part(part, expression)
25312531
- nanosecond
25322532
- dow (day of the week where Sunday is 0)
25332533
- doy (day of the year)
2534-
- epoch (seconds since Unix epoch)
2534+
- epoch (seconds since Unix epoch for timestamps/dates, total seconds for intervals)
25352535
- isodow (day of the week where Monday is 0)
25362536

25372537
- **expression**: Time expression to operate on. Can be a constant, column, or function.

0 commit comments

Comments
 (0)