Convert YYYY-MM-DD to DD-MMM-YYYY in Python

Question:

I’m trying to convert a list of dates (strings) in the format 2023-01-19 into the format 19-Jan-2023. The code I currently have does not work:

date_list = ['2023-01-19', '2023-01-07', '2022-11-29']
new_date_list = []

for date in date_list:
   date_new_format = datetime.datetime(date, '%dd-%mmm-%yyyy')
   new_date_list.append(date_new_format)
Asked By: Greg

||

Answers:

You have to first create a datetime object with strptime, then you can use strftime to reformat it:

from datetime import datetime   

date_list = ['2023-01-19', '2023-01-07', '2022-11-29']    

for date in date_list:
    d = datetime.strptime(date, "%Y-%m-%d")
    date_new_format = datetime.strftime(d, '%d-%b-%Y')
   
    print(date_new_format)
Answered By: Bart Friederichs
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.