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

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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, i.e. 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.

回答1:

You probably just need to assign the result back to the column itself:

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


回答2:

No need apply by using pd.to_datetime

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!