【问题标题】:Presto/SQL - Converting string timestamp to date throws errorPresto/SQL - 将字符串时间戳转换为日期会引发错误
【发布时间】:2019-07-22 21:09:16
【问题描述】:

注意:我在 Qubole 的 presto 和 sql 命令引擎中运行我的查询。

我正在尝试将我的字符串时间戳转换为日期,但没有一个选项有效。

我的字符串时间戳看起来像2017-03-29 10:32:28.0 我想拥有它就像2017-03-29

我尝试了以下查询来将此字符串时间戳转换为检索日期

1. select cast(created as date) from table1

值不能转换为日期:2017-05-26 17:23:58.0

2. select cast(from_iso8601_timestamp(created) as date) from table1

无效格式:“2014-12-19 06:06:36.0”在“06:06:36.0”处格式错误

3. select date(created) from table1

值不能转换为日期:2012-10-24 13:50:00.0

如何在 presto/sql 中将此时间戳转换为日期?

【问题讨论】:

    标签: sql date datetime select presto


    【解决方案1】:

    the documentation 中的解释而言,prestoDB 似乎期望'2001-08-22 03:04:05.321' 格式的时间戳和'2001-08-22' 格式的日期。

    一种解决方案是在转换之前使用a string function 提取字符串的相关部分。我们知道日期部分位于字符串的第一个空格之前,所以。

    如果您需要将日期部分作为 字符串数据类型

    split_part(created, ' ', 1)
    

    如果您需要将日期部分作为 日期数据类型

    cast(split_part(created, ' ', 1) as date)
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用以下解决方案之一:

        SELECT 
        '2017-03-29 10:32:28.0' AS input_string,
        DATE(date_parse('2017-03-29 10:32:28.0', '%Y-%m%-%d %H:%i:%s.%f')) AS solution_1,
        DATE(try_cast('2017-03-29 10:32:28.0' as timestamp)) AS solution_2
      

      【讨论】:

      • try_cast 为我工作,谢谢!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2011-03-16
      相关资源
      最近更新 更多