vendredi 27 mars 2015

How to convert string to datetime with nulls - python, pandas?

I have a series with some datetimes (as strings) and some nulls as 'nan':



import pandas as pd, numpy as np, datetime as dt
df = pd.DataFrame({'Date':['2014-10-20 10:44:31', '2014-10-23 09:33:46', 'nan', '2014-10-01 09:38:45']})


I'm trying to convert these to datetime:



df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))


but I get the error:



time data 'nan' does not match format '%Y-%m-%d %H:%M:%S'


So I try to turn these into actual nulls:



df.ix[df['Date'] == 'nan', 'Date'] = np.NaN


and repeat:



df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))


but then I get the error:



must be string, not float


What is the quickest way to solve this problem?


Thanks :)


Aucun commentaire:

Enregistrer un commentaire