I have the following sample dataframe:
+------------------+-----------+
|order_completed_at|static_date|
+------------------+-----------+
|6/16/2021 21:29 |2021-10-10 |
|6/7/2021 9:29 |2021-10-10 |
|6/12/2021 15:35 |2021-10-10 |
|6/18/2021 22:25 |2021-10-10 |
|6/16/2021 5:25 |2021-10-10 |
+------------------+-----------+
where both fields are of type string. I need to cast these to timestamps, which I can do with the following code:
from pyspark.sql import functions as sql_functions
order_dates = order_dates.withColumn("order_completed_at_test", sql_functions.when() sql_functions.unix_timestamp(
sql_functions.col('order_completed_at'), "MM/dd/yyyy").cast("timestamp"))
order_dates = order_dates.withColumn("static_date_test", sql_functions.to_timestamp("static_date"))
However, within the order_completed_at column, there can be a mix of formats, such that it could be MM/dd/yyyy or yyyy-MM-dd
Is it possible to write one expression that can interpret both date time formats?
EDIT:
I'm going to close this question as it's a very slippery slope to go down this road dealing with dynamic date formats, as both answers have noted. I will be asking the client to make changes to the source data