1

I have two columns in a pandas data frame that I wish to convert to date time variables. One of these columns takes the format of: Jan 17, 2023 at 12:22 PM while the other takes the format of: May 2, 2018.

What is the best way to change them into a format that pandas will recognise as a date?

I have tried a few different solutions but on several occasions have received the following error:

ParserError: day is out of range for month: 0

Connor95
  • 97
  • 4

1 Answers1

3

Do this:

import pandas as pd

df = pd.DataFrame({'date1': ['Jan 17, 2023 at 12:22 PM', 'Feb 1, 2023 at 10:45 AM', 'Mar 4, 2023 at 3:30 PM'],
                   'date2': ['May 2, 2018', 'Jun 5, 2018', 'Jul 7, 2018']})

df['date1'] = pd.to_datetime(df['date1'], format='%b %d, %Y at %I:%M %p')
df['date2'] = pd.to_datetime(df['date2'], format='%b %d, %Y')

print(df)

and you will get

            date1      date2
0 2023-01-17 12:22:00 2018-05-02
1 2023-02-01 10:45:00 2018-06-05
2 2023-03-04 15:30:00 2018-07-07