0

I have a column with the following format:

Original format:

mm/dd/YYYY
10/28/2021
10/28/2021

the output after: print(df['mm/dd/YYYY'])

0 2021-10-28 00:00:00

1 2021-10-28 00:00:00

However when I am trying to convert to datetime I get the following error:

pd.to_datetime(df['mm/dd/YYYY'], format='%Y-%m-%d %H:%M:%S')

time data mm/dd/YYYY doesn't match format specified

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Fred
  • 7
  • 5
  • The values in the `df` don't seem aligned, maybe there are some whitespace characters there? Try pd.to_datetime(df['mm/dd/YYYY'].str.strip(), format='%Y-%m-%d %H:%M:%S'). And please don't post pictures of the data. Look [here](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for some guidelines – Anders Källmar Oct 28 '21 at 19:56
  • Hi, Thank you for the reply. I have edited now my question. I tried your solution but this does not help. There are not whitespace characters in the original file. – Fred Oct 28 '21 at 20:46
  • Just let `pandas` infer the format; use `pd.to_datetime(df['mm/dd/YYYY'])`. – FObersteiner Oct 29 '21 at 05:44

1 Answers1

1

You are passing the wrong format. Try
pd.to_datetime(df['mm/dd/YYYY'], format='%m/%d/%Y')

rvpatel
  • 46
  • 2
  • ValueError: time data '2021-10-28 00:00:00' does not match format '%m/%d/%Y' (match) – Fred Oct 29 '21 at 05:27
  • 1
    Hi, check `df.dtypes`, I think 'mm/dd/YYYY' column is already in datetime64 format. If you want to convert it in another format (string) use .dt.strftime() like `df['mm/dd/YYYY'].dt.strftime('%m-%d-%Y')` – rvpatel Oct 29 '21 at 06:06