pyspark AWS中的String to Date与数据框粘合

iklwldmw  于 2023-08-02  发布在  Spark
关注(0)|答案(2)|浏览(96)

我尝试将数据框中的列从字符串转换为日期,但没有成功,下面是部分代码:

from pyspark.sql.functions import from_unixtime, unix_timestamp, col
from datetime import datetime

## Dynamic Frame to Data Frame
df = Transform0.toDF()

## Substring of time column
## Before: "Thu Sep 03 2020 01:43:52 GMT+0000 (Coordinated Universal Time)""
df = df.withColumn('date_str', substring(df['time'],5,20))
## After: "Sep 03 2020 01:43:52"

## I have tried the following statements with no success
## I use show() in order to see in logs the result

df.withColumn('date_str', datetime.strptime('date_str', '%b %d %Y %H:%M:%S')).show()
df.withColumn(col('date_str'), from_unixtime(unix_timestamp(col('date_str'),"%b %d %Y %H:%M:%S"))).show()
df.withColumn('date_str', to_timestamp('date_str', '%b %d %Y %H:%M:%S')).show()

字符串

qni6mghb

qni6mghb1#

您应该将其分配给另一个数据框变量。
例如:

df = df.withColumn(column, from_unixtime(unix_timestamp(col('date_str'), 'yyyy/MM/dd hh:mm:ss')).cast(
                    types.TimestampType()))
df.show()

字符串

jexiocij

jexiocij2#

尝试在使用spark函数to_timestamp()...etc函数时使用spark datetime

一米

df.show()
#+--------------------+
#|                  ts|
#+--------------------+
#|Sep 03 2020 01:43:52|
#+--------------------+

df.withColumn("ts1",to_timestamp(col("ts"),"MMM dd yyyy hh:mm:ss")).show()
#+--------------------+-------------------+
#|                  ts|                ts1|
#+--------------------+-------------------+
#|Sep 03 2020 01:43:52|2020-09-03 01:43:52|
#+--------------------+-------------------+

字符串

相关问题