【问题标题】:How to convert string to date in databricks sql如何在databricks sql中将字符串转换为日期
【发布时间】:2021-03-03 09:49:42
【问题描述】:

我有一个名为 opens_dt 的列,其中包含字符串格式的时间戳。

+----------------------------+
|        opened_dt           |
+----------------------------+
| 01/01/2015 21:50:00.000000 |
+----------------------------+

跑步

DESCRIBE TABLE 'myTable'

告诉我该列是字符串类型

+-----------+-----------+---------+
| col_name  | data_type | comment |
+-----------+-----------+---------+
| opened_dt | string    | null    |
+-----------+-----------+---------+

我想做什么:

"Show me all entries starting 01.01.2019 until now".
Which I translate to "select * from 'table' where opened_dt >= 01.01.2019".

在此之后,我将 opens_dt 转换为当前日期。

使用时:

SELECT cast(opened_dt AS timestamp) 

只给我

+------------+
| opened_dt  |
+------------+
| null       |
+------------+

使用时:

SELECT to_date(opened_dt AS timestamp) 

只给我

+---------------------------------+
| to_date('myTable'.`opened_dt`)  |
+---------------------------------+
| null                            |
+---------------------------------+

我尝试过的其他尝试但输出错误:

SELECT * FROM 'myTable' WHERE opened_dt >= '01/01/2019 00:00:00.000000' 

SELECT * FROM 'myTable' WHERE opened_dt IN ('%2019%', '%2020%', '%2021%') 

如何将字符串转换为日期以过滤所有早于 01.01.2019 的日期?

我在 DATABRICKS 的 SQL 中寻找一些东西(其他答案在 spark 中)。

【问题讨论】:

    标签: sql apache-spark date apache-spark-sql


    【解决方案1】:

    您可以使用to_timestamp 转换为时间戳类型,并提供与您的列日期格式匹配的日期格式字符串。

    select *
    from myTable
    where to_timestamp(opened_dt, 'dd/MM/yyyy HH:mm:ss.SSSSSS') between to_timestamp('2019-01-01') and current_timestamp()
    

    【讨论】:

    • 感谢您的快速回复。我用 to_timestamp('2021-03-02') 和 to_timestamp('2021-02-03') 对其进行了测试,但我得到的输出是“01/04/2021 16:39:00.000000”
    • 对不起,我不知道你以后有条目。看到编辑的答案? @Wondarar
    • 我也没有哈哈。感谢您的编辑,工作正常:) 同时我尝试了另一次尝试 "WHERE f11.opened_dt LIKE '%2019%' OR f11.opened_dt LIKE '%2020%' OR f11.opened_dt LIKE '%2021%'" 但自从我加入此查询中的 10 个表会导致主要的性能问题。我想问题是通配符是强制性的,以及连接表的数量。
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2015-08-23
    • 2019-10-26
    相关资源
    最近更新 更多