Skip to content

Apache DataFusion SQL Query Engine

Support AT TIME ZONE clause (#9647)

Kunal Kunducf0f8eececd3
diff --git a/datafusion/sql/src/expr/mod.rs b/datafusion/sql/src/expr/mod.rs
index d45a195cb6..a6f1c78c72 100644
--- a/datafusion/sql/src/expr/mod.rs
+++ b/datafusion/sql/src/expr/mod.rs
@@ -576,6 +576,17 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
SQLExpr::Position { expr, r#in } => {
self.sql_position_to_expr(*expr, *r#in, schema, planner_context)
}
+ SQLExpr::AtTimeZone {
+ timestamp,
+ time_zone,
+ } => Ok(Expr::Cast(Cast::new(
+ Box::new(self.sql_expr_to_logical_expr_internal(
+ *timestamp,
+ schema,
+ planner_context,
+ )?),
+ DataType::Timestamp(TimeUnit::Nanosecond, Some(time_zone.into())),
+ ))),
_ => not_impl_err!("Unsupported ast node in sqltorel: {sql:?}"),
}
}
diff --git a/datafusion/sqllogictest/test_files/timestamps.slt b/datafusion/sqllogictest/test_files/timestamps.slt
index 0b8284a45a..f718bbf14c 100644
--- a/datafusion/sqllogictest/test_files/timestamps.slt
+++ b/datafusion/sqllogictest/test_files/timestamps.slt
@@ -2751,3 +2751,39 @@ query I
select to_unixtime(arrow_cast(1599523200.414, 'Float64'));
----
1599523200
+
+##########
+## Tests for the "AT TIME ZONE" clause
+##########
+
+query P
+SELECT '2000-12-01 04:04:12' AT TIME ZONE 'UTC';
+----
+2000-12-01T04:04:12Z
+
+query P
+SELECT '2000-12-01 04:04:12' AT TIME ZONE 'America/New_York';
+----
+2000-12-01T04:04:12-05:00
+
+## date-time strings that already have a explicit timezone can be used with AT TIME ZONE
+
+# same time zone as provided date-time
+query P
+SELECT '2000-12-01T04:04:12-05:00' AT TIME ZONE 'America/New_York';
+----
+2000-12-01T04:04:12-05:00
+
+# different time zone than provided date-time
+query P
+SELECT '2000-12-01T04:04:12-05:00' AT TIME ZONE 'Europe/Berlin';
+----
+2000-12-01T10:04:12+01:00
+
+# longform timezones need whitespace converted to underscore
+statement error
+SELECT '2000-12-01 04:04:12' AT TIME ZONE 'America/New York';
+
+# abbreviated timezone is not supported
+statement error
+SELECT '2023-03-12 02:00:00' AT TIME ZONE 'EDT';
\ No newline at end of file