0

I have a column in my pandas data frame containing dates in the format 'mmddyyyy' with object datatype Eg - 03292021,06262021,01282020....

I'm trying to convert this column into a date column with the format 'mm/dd/yyyy'. Eg - 03/29/2021

Example of the code that I've tried is below:

df['datecol'] = pd.to_datetime(df['datecol'])
df['datecol'] = df['datecol'].dt.strftime('%m/%d/%y')

which gives me the error

month must be in 1..12: 03292021

What changes should be made in the code to get the desired output?

sklal
  • 175
  • 3
  • 15
  • 2
    Use `df['datecol'] = pd.to_datetime(df['datecol'], format='%m%d%Y')` – jezrael May 02 '22 at 12:46
  • 1
    Also not that you don't need the intermediate assignment, you can do `df['datecol'] = pd.to_datetime(df['datecol'], format='%m%d%Y').dt.strftime('%m/%d/%y')` – mozway May 02 '22 at 12:48
  • 1
    Or even: `df['datecol'].str.replace('(..)(..)..(..)', r'\1/\2/\3', regex=True)` – mozway May 02 '22 at 12:49
  • The datatype still shows as 'object'. Why so? How should I change it to 'datetime'? – sklal May 02 '22 at 13:27

0 Answers0