Issue
I need to convert a date string e.g. 2022-04-12T14:22:34Z to timestamp in PySpark/SparkSQL before loading it to a Postgres table.
I have tried SELECT TO_TIMESTAMP(REGEXP_REPLACE('2022-04-12T14:22:34Z', '[TZ]', ''), 'YYYY-MM-DDHH:MM:SS') AS result
It works somewhat, but just wondering if there is an elegant way to accomplish the same in Spark 2.4.
Thanks.
Solution
You can try this:
df.withColumn("date", to_timestamp(col("date"), "yyyy-MM-dd'T'HH:mm:ss'Z'"))
Input:
+--------------------+
| date|
+--------------------+
|2022-04-12T14:22:34Z|
+--------------------+
Output:
+-------------------+
|date |
+-------------------+
|2022-04-12 14:22:34|
+-------------------+
Good luck!
Answered By - vilalabinot Answer Checked By - Senaida (sql.easybugfix Volunteer)
Post a Comment
Post a Comment