Home > Back-end >  Changing text to date on pandas
Changing text to date on pandas

Time:07-01

I have a text column with the format of dd-mmm-yy (e.g.01-Jun-22) for the date. I tried the following code:

df['new_date'] = df['date_text'].dt.strftime('%d/%b/%y')

I'm using this table as a guide (https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) but I got the following error: AttributeError: Can only use .dt accessor with datetimelike values. Will appreciate any advice.

CodePudding user response:

You need to parse the date into a datetime object before you would be able to format it the way you wish.

Pandas has a very convenient to_datetime function that is usually smart enough to recognize the date format in the whole dataframe.

import pandas as pd

df = pd.DataFrame({'date_text': ['01-Jun-22', '02-Jun-22']})
df['datetime'] = pd.to_datetime(df['date_text'])
df['new_text'] = df['datetime'].dt.strftime('%d/%b/%y')

Would produce

   date_text   datetime   new_text
0  01-Jun-22 2022-06-01  01/Jun/22
1  02-Jun-22 2022-06-02  02/Jun/22

  • Related