首页 > 解决方案 > 来自多列的 Pyspark 日期格式

问题描述

我的数据框中有四个字符串列'hour', 'day', 'month', 'year'。我想以格式创建新列 fulldate 'dd/MM/yyyy HH:mm'

df2 = df1.withColumn("fulldate", to_date(concat(col('day'), lit('/'), col('month'), lit('/'), col('year'), lit(' '), col('hour'), lit(':'), lit('0'), lit('0')), 'dd/MM/yyyy HH:mm'))

但它似乎不起作用。我得到格式“yyyy-mm-dd”。

我错过了什么吗?

标签: apache-sparkpysparkapache-spark-sql

解决方案


使用date_format而不是to_date.

to_date将列给定格式转换为日期类型,同时date_format将日期类型列转换为定格式。

from pyspark.sql.functions import date_format, concat, col, lit

df2 = df1.withColumn(
    "fulldate",
    date_format(
        concat(col('year'), lit('/'), col('month'), lit('/'), col('day'), lit(' '), col('hour'), lit(':'), lit('00'), lit(':'), lit('00')),
        'dd/MM/yyyy HH:mm'
    )
)

为了更好的可读性,您可以使用format_string

from pyspark.sql.functions import date_format, format_string, col

df2 = df1.withColumn(
    "fulldate",
    date_format(
        format_string('%d/%d/%d %d:00:00', col('year'), col('month'), col('day'), col('hour')),
        'dd/MM/yyyy HH:mm'
    )
)

推荐阅读