Home > Blockchain >  Pandas, convert datetime format mm/dd/yyyy to dd/mm/yyyy in 2 different columns CSV
Pandas, convert datetime format mm/dd/yyyy to dd/mm/yyyy in 2 different columns CSV

Time:09-07

I'm a beginner in python and i'm trying to convert date from YYYY-mm-dd to dd/mm/YYYY in two different dataframes/columns (StartDate and EndDate) but i'm getting the below error when converting the second column df['StartDate'] even though it works on the first column df['EndDate'].

The Current date on the file is 20220826 and i want 26/08/2022

ValueError: time data '26/08/2022' does not match format '%Y%m%d' (match)

This is my code:

 df=pd.read_csv("AllNewFile.csv")
    df['EndDate'] = pd.to_datetime(df['EndDate'], format='%Y%m%d')
    df['EndDate'] = df['EndDate'].dt.strftime('%d/%m/%Y')
    df.head(10) 
    df['StartDate'] = pd.to_datetime(df['EndDate'], format='%Y%m%d')
    df['StartDate'] = df['StartDate'].dt.strftime('%d/%m/%Y')

Please assist and thank you

CodePudding user response:

Error means not all values in column EndDate are in format YYYYMMDD:

df['EndDate'] = pd.to_datetime(df['EndDate'], format='%d/%m/%Y')

If all values are in YYYYMMDD and some not match format try:

df['EndDate'] = pd.to_datetime(df['EndDate'], format='%Y%m%d', errors='coerce')

Or:

df['EndDate'] = pd.to_datetime(df['EndDate'])
  • Related