Reputation: 401
I use datetime to read time from json, the code for single time works well,
import datetime
data=datetime.datetime.strptime('Apr 12, 2018', '%b %d, Y').strftime('%m/%d/%Y')
However, when I try to apply it into data frame, I have error.
df_newtime=datetime.datetime.strptime(old_df['oldDate'],'%b %d, %Y').strftime('%m/%d/%Y')
the error is TypeError: strptime() argument 1 must be str, not Series
Upvotes: 11
Views: 69507
Reputation: 4080
old_df['oldDate']
will return the column containing the dates, which is a series.
You can solve this issue by using the .apply function in pandas to apply a function to every row of a dataframe. See here
def date_convert(date_to_convert):
return datetime.datetime.strptime(date_to_convert, '%b %d,
%Y').strftime('%m/%d/%Y')
new_df['new_date'] = old_df['oldDate'].apply(date_convert)
Upvotes: 4
Reputation: 21719
You can do it in two ways:
Method 1:
Here we pass a string to the function using map
list(map(lambda x: datetime.datetime.strptime(x,'%b %d, %Y').strftime('%m/%d/%Y'), old_df['oldDate']))
Method 2:
Here we pass a series
pd.to_datetime(old_df['oldDate'], format='%b %d, %Y')
Upvotes: 16