How can i convert from 03MAR23 format to yyyy-mm-dd in python

Question:

I wanted to convert from 03FEB23 format to yyyy-mm-dd in python
how can I do it?

Use the below code:

from pyspark.sql.functions import *
df=spark.createDataFrame([["1"]],["id"])
df.select(current_date().alias("current_date"), 
      date_format("03MAR23","yyyy-MMM-dd").alias("yyyy-MMM-dd")).show()
Asked By: Gaurav Gangwar

||

Answers:

from datetime import datetime

date_str = '03FEB23'
date = datetime.strptime(date_str, '%d%b%y')
formatted_date = date.strftime('%Y-%m-%d')
print(formatted_date) # Output: 2023-02-03
Answered By: PPB

In pyspark:

Try with to_date function with ddMMMyy format.

Examples:

select to_date('03MAR23','ddMMMyy')
--2023-03-03

Dataframe API:

df=spark.createDataFrame([["03MAR23"]],["dt"])
df.withColumn("dt1", to_date(col("dt"),"ddMMMyy")).show()
#+-------+----------+
#|     dt|       dt1|
#+-------+----------+
#|03MAR23|2023-03-03|
#+-------+----------+
Answered By: notNull
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.