Korzak
Korzak

Reputation: 385

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

Upvotes: 1

Views: 5093

Answers (2)

BENY
BENY

Reputation: 323226

No need apply by using pd.to_datetime

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

Upvotes: 2

Zachary Cross
Zachary Cross

Reputation: 2318

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 "")

Upvotes: 5

Related Questions