datafusion_functions/datetime/
to_unixtime.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use super::to_timestamp::ToTimestampSecondsFunc;
19use crate::datetime::common::*;
20use arrow::datatypes::{DataType, TimeUnit};
21use datafusion_common::{exec_err, Result};
22use datafusion_expr::{
23    ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
24};
25use datafusion_macros::user_doc;
26use std::any::Any;
27
28#[user_doc(
29    doc_section(label = "Time and Date Functions"),
30    description = "Converts a value to seconds since the unix epoch (`1970-01-01T00:00:00Z`). Supports strings, dates, timestamps and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono formats](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided.",
31    syntax_example = "to_unixtime(expression[, ..., format_n])",
32    sql_example = r#"
33```sql
34> select to_unixtime('2020-09-08T12:00:00+00:00');
35+------------------------------------------------+
36| to_unixtime(Utf8("2020-09-08T12:00:00+00:00")) |
37+------------------------------------------------+
38| 1599566400                                     |
39+------------------------------------------------+
40> select to_unixtime('01-14-2023 01:01:30+05:30', '%q', '%d-%m-%Y %H/%M/%S', '%+', '%m-%d-%Y %H:%M:%S%#z');
41+-----------------------------------------------------------------------------------------------------------------------------+
42| to_unixtime(Utf8("01-14-2023 01:01:30+05:30"),Utf8("%q"),Utf8("%d-%m-%Y %H/%M/%S"),Utf8("%+"),Utf8("%m-%d-%Y %H:%M:%S%#z")) |
43+-----------------------------------------------------------------------------------------------------------------------------+
44| 1673638290                                                                                                                  |
45+-----------------------------------------------------------------------------------------------------------------------------+
46```
47"#,
48    argument(
49        name = "expression",
50        description = "Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators."
51    ),
52    argument(
53        name = "format_n",
54        description = "Optional [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned."
55    )
56)]
57#[derive(Debug)]
58pub struct ToUnixtimeFunc {
59    signature: Signature,
60}
61
62impl Default for ToUnixtimeFunc {
63    fn default() -> Self {
64        Self::new()
65    }
66}
67
68impl ToUnixtimeFunc {
69    pub fn new() -> Self {
70        Self {
71            signature: Signature::variadic_any(Volatility::Immutable),
72        }
73    }
74}
75
76impl ScalarUDFImpl for ToUnixtimeFunc {
77    fn as_any(&self) -> &dyn Any {
78        self
79    }
80
81    fn name(&self) -> &str {
82        "to_unixtime"
83    }
84
85    fn signature(&self) -> &Signature {
86        &self.signature
87    }
88
89    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
90        Ok(DataType::Int64)
91    }
92
93    fn invoke_with_args(
94        &self,
95        args: datafusion_expr::ScalarFunctionArgs,
96    ) -> Result<ColumnarValue> {
97        let arg_args = &args.args;
98        if arg_args.is_empty() {
99            return exec_err!("to_unixtime function requires 1 or more arguments, got 0");
100        }
101
102        // validate that any args after the first one are Utf8
103        if arg_args.len() > 1 {
104            validate_data_types(arg_args, "to_unixtime")?;
105        }
106
107        match arg_args[0].data_type() {
108            DataType::Int32 | DataType::Int64 | DataType::Null | DataType::Float64 => {
109                arg_args[0].cast_to(&DataType::Int64, None)
110            }
111            DataType::Date64 | DataType::Date32 => arg_args[0]
112                .cast_to(&DataType::Timestamp(TimeUnit::Second, None), None)?
113                .cast_to(&DataType::Int64, None),
114            DataType::Timestamp(_, tz) => arg_args[0]
115                .cast_to(&DataType::Timestamp(TimeUnit::Second, tz), None)?
116                .cast_to(&DataType::Int64, None),
117            DataType::Utf8 => ToTimestampSecondsFunc::new()
118                .invoke_with_args(args)?
119                .cast_to(&DataType::Int64, None),
120            other => {
121                exec_err!("Unsupported data type {:?} for function to_unixtime", other)
122            }
123        }
124    }
125
126    fn documentation(&self) -> Option<&Documentation> {
127        self.doc()
128    }
129}