3

I need to convert a date string to a DateType, but I've several challenges using to_date.

Formatting for day works well (1 or 2 digits), month is a Dutch abbreviation and doesn't work (works only if the abbreviation is equal to English), and year is 2 or 4 digits (missing centuries!).

What's the best way to convert these all to a DateType?
I couldn't find an option to set locale to NL using the formatting.

I created an UDF, but don't know if this is the best way to fix this.
The 19 for century is debatable.

Code:

@F.udf(T.StringType())
def convert_date(s):
    
    month_dict = {"jan":"01", "feb":"02", "mrt":"03", "apr":"04", "mei":"05", "jun":"06", "jul":"07", "aug":"08", "sep":"09", "okt":"10", "nov":"11", "dec":"12" }
    
    day, month, year = s.split("-")
    if len(day) == 1:
        day = '0' + day
    if len(year) < 4:
        year = '19' + year
        
    date = day + "-" + month_dict[month] + "-" + year
        
    return date
  
df = df.withColumn('DateOfBirth_new', F.to_date(convert_date(F.col("DateOfBirth"), "dd-M-yyyy"))

DateFrame:

df = spark.createDataFrame([
 ["2-feb-1966"],
 ["05-mei-1974"],
 ["3-mrt-83"],
 ["05-mrt-1983"],
 ["12-jun-75"]
]).toDF("DateOfBirth")
John Doe
  • 9,843
  • 13
  • 42
  • 73

1 Answers1

1

Here is a similar solution without a UDF, using a when expression for the month conversion.

month_conversion =     F.expr("""CASE 
    WHEN (month = 'jan') THEN 01 
    WHEN (month = 'feb') THEN 02 
    WHEN (month = 'mrt') THEN 03 
    WHEN (month = 'apr') THEN 04 
    WHEN (month = 'mei') THEN 05 
    WHEN (month = 'jun') THEN 06 
    WHEN (month = 'jul') THEN 07 
    WHEN (month = 'aug') THEN 08 
    WHEN (month = 'sep') THEN 09 
    WHEN (month = 'okt') THEN 10 
    WHEN (month = 'nov') THEN 11 
    WHEN (month = 'dec') THEN 12 
    ELSE NULL END
    """).alias("m")

day_conversion = F.when(F.length("day") == 1, F.concat(F.lit("0"), F.col("day"))).otherwise(F.col("day"))
year_conversion = F.when(F.length("year") < 4, F.concat(F.lit("19"), F.col("year"))).otherwise(F.col("year"))

(df.withColumn("split",
    F.split("DateOfBirth", "-")
)
 .withColumn("day",
    F.col("split").getItem(0)
)
 .withColumn("month",
    F.col("split").getItem(1)
)
.withColumn("year",
    F.col("split").getItem(2)
)
 .select(
    F.concat_ws("-",
        day_conversion,
        month_conversion,
        year_conversion
    ).alias("DateOfBirth_new")
)
.show())
Thijs
  • 236
  • 1
  • 5