Home > OS >  Time data error when amending dataframe column using function in Python
Time data error when amending dataframe column using function in Python

Time:11-27

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')
  • Related