Home > Software engineering >  How to pass pandas column inside datatime
How to pass pandas column inside datatime

Time:07-22

I want to parse a list or pandas column ex: 21/01/2005, 22/01/2005 and covert them to 21 January 2005. But I get this error: strptime() argument 1 must be str, not Series

import datetime
import pandas as pd

data_dict = {
            'date': ['21/01/2022', '22/01/2022']
          }
df = pd.DataFrame(data_dict)
datetime.datetime.strptime(df['date'], '%d/%m/%Y').strftime('%d %B %Y')

CodePudding user response:

You can use apply to apply the strptime/strftime functions to each element in the column.

df['date'] = df['date']
.apply(datetime.datetime.strptime, args=('%d/%M/%Y', ))
.apply(datetime.datetime.strftime, args=('%d %B %Y',))

Alternatively, to_datetime will be more appropriate for your use case.

Refer to this question for more.

CodePudding user response:

The to_datetime is a useful command here:

from pandas import DataFrame, to_datetime

data_dict = {"date": ["21/01/2022", "22/01/2022"]}

df = DataFrame(data_dict)

df["parsed_date"] = to_datetime(df["date"], format="%d/%m/%Y")
  • Related