Pyspark日期yyyy-mmm-dd转换

时间:2018-05-30 14:18:53

标签: pyspark pyspark-sql

有一个火花数据框。其中一个col的日期填充的格式为2018-Jan-12

我需要将此结构更改为20180112

如何实现

3 个答案:

答案 0 :(得分:1)

调查Python的日期时间库以及方法strftime()strptime()Basic date and time types: trftime() and strptime()

例如,使用strftime.org作为参考:

from datetime import datetime

date_string = '2018-Jan-12'
# Assuming day of the month is a zero-padded decimal number
datetime_object = datetime.strptime(date_string, '%Y-%b-%d')
converted_date_string = datetime_object.strftime('%Y%m%d')

答案 1 :(得分:0)

您可以使用Pyspark UDF

from pyspark.sql import functions as f
from pyspark.sql import types as t
from datetime.datetime import strftime, strptime

df = df.withColumn('date_col', f.udf(lambda d: strptime(d, '%Y-%b-%d').strftime('%Y%m%d'), t.StringType())(f.col('date_col')))

或者,您可以定义一个大函数来捕获异常(如果需要)。

def date_converter(col):
    try:
        _date = strptime(date_string, '%Y-%b-%d')
        str_date = _date.strftime('%Y%m%d')
        return str_date
    except Exception:
        # Some code if needed
        return ''

udf_function = f.udf(date_converter, t.StringType())

df = df.withColumn('date_col', udf_function(df.date_col))

注意:我假设date_col是您列的名称。

答案 2 :(得分:0)

适用于Spark版本1.5 +

假设您有以下DataFrame:

df = sqlCtx.createDataFrame([("2018-Jan-12",)], ["date_str"])
df.show()
#+-----------+
#|   date_str|
#+-----------+
#|2018-Jan-12|
#+-----------+

为避免使用udf,您可以先convert the string to a date

from pyspark.sql.functions import from_unixtime, unix_timestamp
df = df.withColumn('date', from_unixtime(unix_timestamp('date_str', 'yyyy-MMM-dd')))
df.show()
#+-----------+-------------------+
#|   date_str|               date|
#+-----------+-------------------+
#|2018-Jan-12|2018-01-12 00:00:00|
#+-----------+-------------------+

然后以您想要的格式format the date as a string

from pyspark.sql.functions import date_format, col
df = df.withColumn("new_date_str", date_format(col("date"), "yyyyMMdd"))
df.show()
#+-----------+-------------------+------------+
#|   date_str|               date|new_date_str|
#+-----------+-------------------+------------+
#|2018-Jan-12|2018-01-12 00:00:00|    20180112|
#+-----------+-------------------+------------+

或者如果您愿意,可以将它们全部链接在一起并跳过中间步骤:

import pyspark.sql.functions as f
df.select(
    f.date_format(
        f.from_unixtime(
            f.unix_timestamp(
                'date_str',
                'yyyy-MMM-dd')
        ),
        "yyyyMMdd"
    ).alias("new_date_str")
).show()
#+------------+
#|new_date_str|
#+------------+
#|    20180112|
#+------------+