火花 >= 2.2
你可以跳过unix_timestamp
并投射和使用to_date
or to_timestamp
:
from pyspark.sql.functions import to_date, to_timestamp
df_test.withColumn("date", to_date("date", "dd-MMM-yy")).show()
## +---+----------+
## | id| date|
## +---+----------+
## | 1|2015-07-14|
## | 2|2015-06-14|
## | 3|2015-10-11|
## +---+----------+
df_test.withColumn("date", to_timestamp("date", "dd-MMM-yy")).show()
## +---+-------------------+
## | id| date|
## +---+-------------------+
## | 1|2015-07-14 00:00:00|
## | 2|2015-06-14 00:00:00|
## | 3|2015-10-11 00:00:00|
## +---+-------------------+
然后应用如下所示的其他日期时间函数。
火花
不可能在一次访问中派生多个顶级列。您可以将结构或集合类型与 UDF 一起使用,如下所示:
from pyspark.sql.types import StringType, StructType, StructField
from pyspark.sql import Row
from pyspark.sql.functions import udf, col
schema = StructType([
StructField("day", StringType(), True),
StructField("month", StringType(), True),
StructField("year", StringType(), True)
])
def split_date_(s):
try:
d, m, y = s.split("-")
return d, m, y
except:
return None
split_date = udf(split_date_, schema)
transformed = df_test.withColumn("date", split_date(col("date")))
transformed.printSchema()
## root
## |-- id: long (nullable = true)
## |-- date: struct (nullable = true)
## | |-- day: string (nullable = true)
## | |-- month: string (nullable = true)
## | |-- year: string (nullable = true)
但 PySpark 中它不仅相当冗长,而且价格昂贵。
对于基于日期的转换,您可以简单地使用内置函数:
from pyspark.sql.functions import unix_timestamp, dayofmonth, year, date_format
transformed = (df_test
.withColumn("ts",
unix_timestamp(col("date"), "dd-MMM-yy").cast("timestamp"))
.withColumn("day", dayofmonth(col("ts")).cast("string"))
.withColumn("month", date_format(col("ts"), "MMM"))
.withColumn("year", year(col("ts")).cast("string"))
.drop("ts"))
同样你可以使用regexp_extract
分割日期字符串。
也可以看看从 Spark DataFrame 中的单个列派生多个列
Note:
如果您使用未打补丁的版本SPARK-11724这将需要之后更正unix_timestamp(...)
和之前cast("timestamp")
.