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
The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.
Python DateTime – strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With