I have a date column in my Spark DataDrame that contains multiple string formats. I would like to cast these to DateTime.
The two formats in my column are:
mm/dd/yyyy; andyyyy-mm-dd
My solution so far is to use a UDF to change the first date format to match the second as follows:
import re
def parseDate(dateString):
if re.match('\d{1,2}\/\d{1,2}\/\d{4}', dateString) is not None:
return datetime.strptime(dateString, '%M/%d/%Y').strftime('%Y-%M-%d')
else:
return dateString
# Create Spark UDF based on above function
dateUdf = udf(parseDate)
df = (df.select(to_date(dateUdf(raw_transactions_df['trans_dt']))))
This works, but is not all that fault-tolerant. I am specifically concerned about:
- Date formats I am yet to encounter.
- Distinguishing between
mm/dd/yyyyanddd/mm/yyyy(the regex I'm using clearly doesn't do this at the moment).
Is there a better way to do this?


