在Pyspark中将列类型从字符串更改为日期

10
3个回答

14
from pyspark.sql.functions import col, unix_timestamp, to_date

#sample data
df = sc.parallelize([['12-21-2006'],
                     ['05-30-2007'],
                     ['01-01-1984'],
                     ['12-24-2017']]).toDF(["date_in_strFormat"])
df.printSchema()

df = df.withColumn('date_in_dateFormat', 
                   to_date(unix_timestamp(col('date_in_strFormat'), 'MM-dd-yyyy').cast("timestamp")))
df.show()
df.printSchema()

输出结果为:

root
 |-- date_in_strFormat: string (nullable = true)

+-----------------+------------------+
|date_in_strFormat|date_in_dateFormat|
+-----------------+------------------+
|       12-21-2006|        2006-12-21|
|       05-30-2007|        2007-05-30|
|       01-01-1984|        1984-01-01|
|       12-24-2017|        2017-12-24|
+-----------------+------------------+

root
 |-- date_in_strFormat: string (nullable = true)
 |-- date_in_dateFormat: date (nullable = true)

哎呀,这确实有所帮助,但只是部分地解决了问题 :( 一些日期仍然返回空值。好像只有一些得到转换? - Tata
您需要检查字符串列中的日期格式。它应该是 MM-dd-yyyy,否则将返回 null - Prem
我的日期原始字符串是以dd/MM/yyyy的格式编写的。我在你编写的代码中使用了它,就像我说的那样,只有一部分被转换为日期类型... - Tata

5

简单的方法:

from pyspark.sql.types import *
df_1 = df.withColumn("col_with_date_format",
df["col_with_date_format"].cast(DateType()))

4

使用默认的to_date函数是一种更简单的方法:

from pyspark.sql import functions as F
df= df.withColumn('col_with_date_format',F.to_date(df.col_with_str_format))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接