Abdullahsab3 commented on code in PR #11347:
URL: https://github.com/apache/datafusion/pull/11347#discussion_r1670830134


##########
datafusion/functions/src/datetime/to_local_time.rs:
##########
@@ -0,0 +1,601 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::any::Any;
+use std::ops::Add;
+use std::sync::Arc;
+
+use arrow::array::timezone::Tz;
+use arrow::array::{ArrayRef, PrimitiveArray};
+use arrow::datatypes::DataType::Timestamp;
+use arrow::datatypes::{
+    ArrowTimestampType, DataType, TimestampMicrosecondType, 
TimestampMillisecondType,
+    TimestampNanosecondType, TimestampSecondType,
+};
+use arrow::datatypes::{
+    TimeUnit,
+    TimeUnit::{Microsecond, Millisecond, Nanosecond, Second},
+};
+
+use chrono::{Offset, TimeDelta, TimeZone, Utc};
+use datafusion_common::cast::as_primitive_array;
+use datafusion_common::{exec_err, Result, ScalarValue};
+use datafusion_expr::TypeSignature::Exact;
+use datafusion_expr::{
+    ColumnarValue, ScalarUDFImpl, Signature, Volatility, TIMEZONE_WILDCARD,
+};
+
+/// A UDF function that converts a timezone-aware timestamp to local time 
(with no offset or
+/// timezone information). In other words, this function strips off the 
timezone from the timestamp,
+/// while keep the display value of the timestamp the same.
+///
+/// # Example 1
+///
+/// ```
+/// # use datafusion_common::ScalarValue;
+/// # use datafusion_expr::ColumnarValue;
+/// # use datafusion_functions::datetime::to_local_time::ToLocalTimeFunc;
+/// # use datafusion_expr::ScalarUDFImpl;
+///
+/// // 2019-03-31 01:00:00 +01:00
+/// let res = ToLocalTimeFunc::new()
+///     .invoke(&[ColumnarValue::Scalar(ScalarValue::TimestampSecond(
+///         Some(1_553_990_400),
+///         Some("Europe/Brussels".into()),
+///     ))])
+///     .unwrap();
+///
+/// // 2019-03-31 01:00:00 <-- this timestamp no longer has +01:00 offset
+/// let expected = ScalarValue::TimestampSecond(Some(1_553_994_000), None);
+///
+/// match res {
+///   ColumnarValue::Scalar(res) => {
+///       assert_eq!(res, expected);
+///   }
+///   _ => panic!("unexpected return type"),
+/// }
+/// ```
+///
+/// # Example 2
+///
+/// ```
+/// # use datafusion_common::ScalarValue;
+/// # use datafusion_expr::ColumnarValue;
+/// # use chrono::NaiveDateTime;
+/// # use datafusion_functions::datetime::to_local_time::ToLocalTimeFunc;
+/// # use datafusion_expr::ScalarUDFImpl;
+///
+/// let timestamp_str = "2020-03-31T13:40:00";
+/// let timezone_str = "America/New_York";
+/// let tz: arrow::array::timezone::Tz =
+///     timezone_str.parse().expect("Invalid timezone");
+///
+/// let timestamp = timestamp_str
+///     .parse::<NaiveDateTime>()
+///     .unwrap()
+///     .and_local_timezone(tz) // this is in a local timezone
+///     .unwrap()
+///     .timestamp_nanos_opt()
+///     .unwrap();
+///
+/// let expected_timestamp = timestamp_str
+///     .parse::<NaiveDateTime>()
+///     .unwrap()
+///     .and_utc() // this is in UTC
+///     .timestamp_nanos_opt()
+///     .unwrap();
+///
+/// let input =
+///     ScalarValue::TimestampNanosecond(Some(timestamp), 
Some(timezone_str.into()));
+/// let res = ToLocalTimeFunc::new()
+///     .invoke(&[ColumnarValue::Scalar(input)])
+///     .unwrap();
+/// let expected = ScalarValue::TimestampNanosecond(Some(expected_timestamp), 
None);
+/// match res {
+///     ColumnarValue::Scalar(res) => {
+///         assert_eq!(res, expected);
+///         }
+///     _ => panic!("unexpected return type"),
+/// }
+/// ```
+#[derive(Debug)]
+pub struct ToLocalTimeFunc {
+    signature: Signature,
+}
+
+impl Default for ToLocalTimeFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl ToLocalTimeFunc {
+    pub fn new() -> Self {
+        let base_sig = |array_type: TimeUnit| {
+            vec![
+                Exact(vec![Timestamp(array_type, None)]),
+                Exact(vec![Timestamp(array_type, 
Some(TIMEZONE_WILDCARD.into()))]),
+            ]
+        };
+
+        let full_sig = [Nanosecond, Microsecond, Millisecond, Second]
+            .into_iter()
+            .map(base_sig)
+            .collect::<Vec<_>>()
+            .concat();
+
+        Self {
+            signature: Signature::one_of(full_sig, Volatility::Immutable),
+        }
+    }
+
+    fn to_local_time(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
+        if args.len() != 1 {
+            return exec_err!(
+                "to_local_time function requires 1 argument, got {}",
+                args.len()
+            );
+        }
+
+        let time_value = args[0].clone();
+        let arg_type = time_value.data_type();
+        match arg_type {
+            DataType::Timestamp(_, None) => {
+                // if no timezone specificed, just return the input
+                Ok(time_value.clone())
+            }
+            // if has timezone, adjust the underlying time value. the current 
time value
+            // is stored as i64 in UTC, even though the timezone may not be in 
UTC, so
+            // we need to adjust the time value to the local time. see 
[`adjust_to_local_time`]
+            // for more details.
+            //
+            // Then remove the timezone in return type, i.e. return None
+            DataType::Timestamp(_, Some(_)) => match time_value {
+                ColumnarValue::Scalar(ScalarValue::TimestampNanosecond(
+                    Some(ts),
+                    Some(tz),
+                )) => {
+                    let adjusted_ts =
+                        adjust_to_local_time::<TimestampNanosecondType>(ts, 
&tz);
+                    Ok(ColumnarValue::Scalar(ScalarValue::TimestampNanosecond(
+                        Some(adjusted_ts),
+                        None,
+                    )))
+                }
+                ColumnarValue::Scalar(ScalarValue::TimestampMicrosecond(
+                    Some(ts),
+                    Some(tz),
+                )) => {
+                    let adjusted_ts =
+                        adjust_to_local_time::<TimestampMicrosecondType>(ts, 
&tz);
+                    Ok(ColumnarValue::Scalar(ScalarValue::TimestampMicrosecond(
+                        Some(adjusted_ts),
+                        None,
+                    )))
+                }
+                ColumnarValue::Scalar(ScalarValue::TimestampMillisecond(
+                    Some(ts),
+                    Some(tz),
+                )) => {
+                    let adjusted_ts =
+                        adjust_to_local_time::<TimestampMillisecondType>(ts, 
&tz);
+                    Ok(ColumnarValue::Scalar(ScalarValue::TimestampMillisecond(
+                        Some(adjusted_ts),
+                        None,
+                    )))
+                }
+                ColumnarValue::Scalar(ScalarValue::TimestampSecond(
+                    Some(ts),
+                    Some(tz),
+                )) => {
+                    let adjusted_ts =
+                        adjust_to_local_time::<TimestampSecondType>(ts, &tz);
+                    Ok(ColumnarValue::Scalar(ScalarValue::TimestampSecond(
+                        Some(adjusted_ts),
+                        None,
+                    )))
+                }
+                ColumnarValue::Array(array) => {
+                    fn transform_array<T>(
+                        array: &ArrayRef,
+                        tz: &str,
+                    ) -> Result<ColumnarValue>
+                    where
+                        T: ArrowTimestampType,
+                    {
+                        let array = as_primitive_array::<T>(array)?;
+                        let array: PrimitiveArray<T> =
+                            array.unary(|ts| adjust_to_local_time::<T>(ts, 
tz));

Review Comment:
   minor remark: You can have both `array` definitions in the same definition 
to avoid shadowing
   ```suggestion
                           let array = 
as_primitive_array::<T>(array)?.unary(|ts| adjust_to_local_time::<T>(ts, tz));
   ```
   (my linting might be off :p) 
   
   Thinking outloud here, but perhaps it's better to follow the same naming 
convention as for the scalar types. i.e:
   ```suggestion
                           let array = as_primitive_array::<T>(array)?;
                           let adjusted_array = .unary(|ts| 
adjust_to_local_time::<T>(ts, tz));
   ```
   in which case the returned value needs to be changed to:
   ```Rust
    Ok(ColumnarValue::Array(Arc::new(adjusted_array)))
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to