How to convert date patterns using regex python

Question:

I want to convert date from these two formats 21/01/2022 and 21-Jan-22 into 21 Jan 2022. Format needed day(2 int) month(3 string) year(4 int). Thanks

import pandas as pd

data_dict = {
            'date': ['I paid USD 10,000.00 on 21/01/2022 for car service',
                     'I paid USD 10,000.00 on 21-Jan-22 for car service'
                    ]
          }
df = pd.DataFrame(data_dict)
Asked By: AK007

||

Answers:

You can use a regex and pandas.to_datetime:

regex = r'(dd/dd/d{4}|d{1,2}-[a-zA-Z]{3}-d{2})'
df['new'] = (pd.to_datetime(df['date'].str.extract(regex, expand=False),
                            dayfirst=True)
               .dt.strftime('%d %b %y')
             )

output:

                                                date        new
0  I paid USD 10,000.00 on 21/01/2022 for car ser...  21 Jan 22
1  I paid USD 10,000.00 on 21-Jan-22 for car service  21 Jan 22
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.