I am trying to set date format to a pandas dataframe column.
test['Date']=pd.to_datetime(test['Date'], format='%d-%m-%Y')
However, I get this error:
ValueError: time data '13/04/2021 15:21' does not match format '%d-%m
m-%Y' (match)
Why I cannot format this date column to day-month-year format?
CodePudding user response:
IIUC, you want to keep only the date part, so truncate your string before to_datetime
:
test = pd.DataFrame({'Date': ['13/04/2021 15:21']})
test['Date'] = pd.to_datetime(test['Date'].str[:10], format='%d/%m/%Y')
print(test)
# Output:
Date
0 2021-04-13
CodePudding user response:
You can either leave the format keyword out entirely, and pandas will automatically detect the format, or change it to match the format indicated. I'd suggest leaving it out, in case your column has different formats included.
But this would work for the value indicated:
test['Date'] = pd.to_datetime(test['Date'], format='%d/%m/%Y %H:%M')