Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strptime() argument 1 must be str, not Series time series convert

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

like image 577
qing zhangqing Avatar asked Apr 30 '18 23:04

qing zhangqing


People also ask

What is Strptime ()?

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.

What does DateTime DateTime Strptime do?

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.

What is the difference between Strftime and Strptime in Python?

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.


2 Answers

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')
like image 157
YOLO Avatar answered Oct 06 '22 00:10

YOLO


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)
like image 45
sakurashinken Avatar answered Oct 06 '22 00:10

sakurashinken