简体   繁体   中英

TypeError: strptime() argument 1 must be str, not Series

I am trying to apply strptime to a pandas series like the following:

    df['inward_date'] = datetime.strptime(df['inward_date'][:10], "%Y-%m-%d").strftime("%d-%m-%Y")

but it gives the above stated error. I can apply the loop and change it one by one but what is the more pythonic way to do this?

You need to apply this conversion operation for every row item of your DataFrame, therefore use df.apply function eg to create a new pd.Series object and then assign it to the needed column.

df['inward_date'] = df['inward_date'].apply(lambda x: datetime.strptime(x[:10], "%Y-%m-%d").strftime("%d-%m-%Y"))

Pandas has a simple conversion method:

import pandas as pd
# convert the 'Date' column to datetime format
df['Date']= pd.to_datetime(df['Date'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM