I want to change the format of a dataframe column from YYYY-MM-DD to DD/MM/YYYY. I do this using:
df['Start Date'] = pd.to_datetime(df['Start Date'], format='%Y-%m-%d')
df['Start Date'] = df['Start Date'].apply(lambda x: x.strftime('%d/%m/%Y'))
I want to do this now in a function:
def datesqltoexcel(df,dtcol):
x = df
y = dtcol
z = x '[' y ']'
z = pd.to_datetime(z, format='%Y-%m-%d')
z = z.apply(lambda a: a.strftime('%d/%m/%Y'))
datesqltoexcel('df','Start Date')
But I am getting the error 'ValueError: time data df[Start Date] doesn't match format specified'. Could someone advise please.
CodePudding user response:
I think first solution is best use, because vectorized, apply are loops under the hood:
def datesqltoexcel(df,dtcol):
df[dtcol] = pd.to_datetime(df[dtcol], format='%Y-%m-%d').dt.strftime('%d/%m/%Y')
return df
datesqltoexcel(df,'Start Date')