LMLPP
LMLPP

Reputation: 105

Need to convert entire column from string format to date format from a Dataframe

I am trying to convert an entire column from a Dataframe from a string to date format. Does anyone have any recommendations on how to do this?

I've successfully been able to change one element of this using strptime, but not sure the best way to apply this to the entire column:

Sample of the raw Data:

2016/06/28 02:13:51

In:

Var1 = Dataframename['columnname'][0]
temp = datetime.datetime.strptime(Var1, '%Y/%m/%d  %H:%M:%S')
temp

Out:

datetime.datetime(2016, 6, 28, 2, 13, 51)

Upvotes: 3

Views: 2433

Answers (2)

Sociopath
Sociopath

Reputation: 13401

I think you are looking for this

import datetime
data['colname']=data['colname'].apply(lambda x:datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S"))

Upvotes: 3

jezrael
jezrael

Reputation: 862641

You can use to_datetime:

df = pd.DataFrame({'b':['2016/06/28 02:13:51','2016/06/28 02:13:51','2016/06/28 02:13:51'],
                   'a':[4,5,6]})

print (df)
   a                    b
0  4  2016/06/28 02:13:51
1  5  2016/06/28 02:13:51
2  6  2016/06/28 02:13:51

df['b'] = pd.to_datetime(df.b)
print (df)
   a                   b
0  4 2016-06-28 02:13:51
1  5 2016-06-28 02:13:51
2  6 2016-06-28 02:13:51
print (df.dtypes)
a             int64
b    datetime64[ns]
dtype: object

Upvotes: 2

Related Questions