Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Time data error when amending dataframe column using function in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading