【问题标题】:Unable to successfully extract timestamp to date and time in pyspark无法在 pyspark 中成功提取时间戳到日期和时间
【发布时间】:2020-07-13 20:55:30
【问题描述】:

我无法从时间戳中提取时间和日期。数据被读取为字符串,所以我看到人们能够使用date_format 将其本质上转换为我们想要的格式。这是我在下面尝试过的

import pyspark.sql.functions as F
from pyspark.sql.functions import date_format

data = df_data.select(date_format(F.col("timestamp"),"MM/d/yy").alias("date"),
        date_format(F.col("timestamp"),"HH:mm").alias("time"),
        date_format(F.col("timestamp"), "M/d/yy").alias("current_date_formated")).show(10)

我的输入数据如下所示:

时间戳 11/9/18 14:11 11/9/18 14:27 11/9/18 14:42 11/9/18 14:57

上面代码的输出是在我的datetime 别名下返回null 的行。我也尝试过使用to_date,但也没有用

import pyspark.sql.functions as F

data = df_data.select(date_format(F.col("timestamp"),"MM/d/yy").alias("date"),
        F.to_date(F.col("timestamp"),"HH:mm").alias("time"),
        F.to_date(F.col("timestamp"), "M/d/yy").alias("current_date_formated")).show(10)

【问题讨论】:

    标签: python pyspark timestamp


    【解决方案1】:

    date_format 的想法是正确的。您唯一缺少的是首先将您的字符串时间戳转换为时间戳类型。然后你可以进行格式化。我假设你的input data的格式是day-month-year,如果不是,你可以切换成"MM/dd/yy HH:mm"

    from pyspark.sql import functions as F
    df.withColumn("timestamp", F.to_timestamp("timestamp","dd/MM/yy HH:mm"))\
      .withColumn("time",F.date_format("timestamp","HH:mm"))\
      .withColumn("current_date_formated",F.date_format("timestamp", "M/d/yy")).show()
    
    +-------------------+-----+---------------------+
    |          timestamp| time|current_date_formated|
    +-------------------+-----+---------------------+
    |2018-09-11 14:11:00|14:11|              9/11/18|
    |2018-09-11 14:27:00|14:27|              9/11/18|
    |2018-09-11 14:42:00|14:42|              9/11/18|
    |2018-09-11 14:57:00|14:57|              9/11/18|
    +-------------------+-----+---------------------+
    

    【讨论】:

    • 一切似乎都返回空值。此外,当我打印每列的类型时,它以字符串形式返回,这很令人困惑,因为我们在使用 date_format 时正在转换列。
    • 您不会使用 date_format 转换任何内容,因为它仅在 datetypetimestamptype 上运行。使用我上面的代码
    • 之前你可以申请date_format,你需要convert你的string时间戳到时间戳类型
    • 我刚刚开始工作!每次格式化日期时,我都需要将日期格式设置为"M/d/yy"
    猜你喜欢
    • 2020-01-08
    • 2017-02-01
    • 2020-06-27
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多