【问题标题】:Spark-Java:How to convert Dataset string column of format "yyyy-MM-ddThh:mm:ss.SSS+0000" to timestamp with a format?Spark-Java:如何将格式为“yyyy-MM-ddThh:mm:ss.SSS+0000”的数据集字符串列转换为时间戳格式?
【发布时间】:2019-07-08 11:22:43
【问题描述】:

我有一个数据集,其中有一列 lastModified 的字符串类型,格式为“yyyy-MM-ddThh:mm:ss.SSS+0000”(示例数据:2018-08-17T19:58:46.000+0000)。

我必须添加一个时间戳类型的新列 lastModif_mapped,方法是将 lastModified 的值转换为格式“yyyy-MM-dd hh:mm:ss.SSS强>”。

我尝试了下面的代码,但新列正在获取值 null

Dataset<Row> filtered = null;
filtered = ds1.select(ds1.col("id"),ds1.col("lastmodified"))
                .withColumn("lastModif_mapped", functions.unix_timestamp(ds1.col("lastmodified"), "yyyy-MM-dd HH:mm:ss.SSS").cast("timestamp")).alias("lastModif_mapped");

我哪里错了?

【问题讨论】:

    标签: apache-spark apache-spark-sql timestamp apache-spark-dataset


    【解决方案1】:
    1. 正如我在您最初的问题中所回答的,您的输入数据字符串字段与unix_timestamp(Column s, String p) 的允许格式不对应:

    如果是字符串,则数据必须采用可以转换为时间戳的格式,例如 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss.SSSS

    1. 对于你的情况,你需要使用to_timestamp(Column s, String fmt)
    import static org.apache.spark.sql.functions.to_timestamp;
    ...
    to_timestamp(ds1.col("lastmodified"), "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
    

    而且您不需要显式转换为 Timestamp,因为 to_timestamp 已经返回 Timestamp。

    1. 使用withColumn("lastModif_mapped",...) 时,无需添加alias("lastModif_mapped"),因为withColumn 会使用提供的名称创建一个新列。

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2021-03-15
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多