简体   繁体   中英

Python - convert date string from YYYY-MM-DD to DD-MMM-YYYY using datetime?

So I have read a number of threads on this, and am still stumped. Any help would be sincerely appreciated.

I have a column in a dataframe that contains strings of dates, or nothing. Strings are in this format: 2017-10-17 , ie YYYY-MM-DD .

I want to convert these to DD-MMM-YYYY , so the above would read 17-Oct-2017 .

Here is the code that I have, which seems to do nothing. It doesn't error out, but it doesn't actually modify the dates; they are the same as before. I'm calling this in the beginning: import datetime

df_combined['VisitDate'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%d-%b-%Y') if x != "" else "")

I expected this to return a string in a different format than the format the original string was in when it's read from the column.

您可能只需要将结果分配回列本身即可:

df_combined['VisitDate'] = df_combined['VisitDate'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%d-%b-%Y') if x != "" else "")

无需使用pd.to_datetime apply

pd.to_datetime(df_combined['VisitDate'],errors='coerce',format='%d-%b-%Y').fillna('')

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