简体   繁体   中英

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM