【问题标题】:what is the best way to cast or handle the date datatype in pyspark在 pyspark 中转换或处理日期数据类型的最佳方法是什么
【发布时间】:2021-08-24 18:18:35
【问题描述】:

您能帮我以更好的方式在 pyspark 中转换以下数据类型吗?我们无法在数据框中处理这个问题。

输入:

Aug 11, 2020 04:34:54.0 PM

到预期输出:

2020-08-11 04:34:54:00 PM

【问题讨论】:

    标签: date pyspark aws-glue aws-glue-data-catalog


    【解决方案1】:

    尝试使用 from_unixtime, unix_timestamp 函数。

    Example:

    #sample data in dataframe
    df.show(10,False)
    #+--------------------------+
    #|ts                        |
    #+--------------------------+
    #|Aug 11, 2020 04:34:54.0 PM|
    #+--------------------------+
    
    df.withColumn("dt",from_unixtime(unix_timestamp(col("ts"),"MMM d, yyyy hh:mm:ss.SSS a"),"yyyy-MM-dd hh:mm:ss.SSS a")).\
    show(10,False)
    #+--------------------------+--------------------------+
    #|ts                        |dt                        |
    #+--------------------------+--------------------------+
    #|Aug 11, 2020 04:34:54.0 PM|2020-08-11 04:34:54.000 PM|
    #+--------------------------+--------------------------+
    

    如果您希望新列为时间戳类型,请在 spark 中使用 to_timestamp 函数。

    df.withColumn("dt",to_timestamp(col("ts"),"MMM d, yyyy hh:mm:ss.SSS a")).\
    show(10,False)
    #+--------------------------+-------------------+
    #|ts                        |dt                 |
    #+--------------------------+-------------------+
    #|Aug 11, 2020 04:34:54.0 PM|2020-08-11 16:34:54|
    #+--------------------------+-------------------+
    
    df.withColumn("dt",to_timestamp(col("ts"),"MMM d, yyyy hh:mm:ss.SSS a")).printSchema()
    #root
    # |-- ts: string (nullable = true)
    # |-- dt: timestamp (nullable = true)
    

    【讨论】:

    • YYYY-MM-DD HH24:MI:SS 在 pyspark 中转换数据时间戳。如何做到这一点。
    • @Suganya,您能否通过打开新问题并在问题中标记我来分享一些示例数据。我会尽力提供帮助。
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 2011-06-30
    • 2018-03-16
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多