【问题标题】:How to change the string to timestamp in Pyspark?如何在 Pyspark 中将字符串更改为时间戳?
【发布时间】:2019-03-25 11:10:01
【问题描述】:

我正在尝试使用以下数据集和 api 将字符串更改为 pyspark(Spark 版本 = 2.3.0)中的时间戳

我一直在尝试与堆栈溢出不同的分辨率,但没有什么可以帮助更改为 time_stamp

df:
|Customer|Transaction_Timestamp|Transaction_Base_Point_Value|
+--------+---------------------+----------------------------+
|Cust1   |10/25/2017 1:47      |2000                        |

尝试 1

df2 = df.select('Customer', 'Transaction_Timestamp','Transaction_Base_Point_Value', unix_timestamp('Transaction_Timestamp', "dd/MM/yy HH:mm") .cast(TimestampType()).alias("Timestamp")).show(1, False)

尝试 2

df.withColumn('Time', to_timestamp("Transaction_Timestamp", "yyyy_MM_dd hh_mm_ss").cast("Timestamp"))

尝试 3

change_type= df.withColumn('Timestamp', col='Transaction_Timestamp').cast('timestamp')

但是,架构会产生以下输出

 |-- Timestamp: timestamp (nullable = true)

我需要得到如下输出,以便我可以对时间戳执行其他操作

|Customer|Transaction_Timestamp|Transaction_Base_Point_Value|Timestamp|
+--------+---------------------+----------------------------+---------+
|   Cust1|      10/25/2017 1:47|                        2000|     10/25/2017 1:47|

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql


    【解决方案1】:

    pyspark.sql.functions使用to_timestamp

    .withColumn('Timestamp', to_timestamp('Transaction_Timestamp', 'MM/dd/yyyy hh:mm'))
    

    如果没有1:47 而是01:47,也可以使用填充小时值

    【讨论】:

    • 您好 Kendoka,感谢您的重播。但是,上述解决方案对我不起作用。即使架构发生更改,时间戳仍然会抛出 Null 值。
    • 你可以试试col("Transaction_Timestamp").cast("Timestamp")我想知道零填充时间字符串是否会改变......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多