In Python Pandas, How Can I Convert This Formatted Date String To Datetime
I have tried several ways of using to_datetime, but so far I can only get it to return the dtype as 'object' pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),dayfirst=True) Th
Solution 1:
You can pass a format
parameter to the to_datetime
function.
>>>import pandas as pd>>>df = pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),format="%d%b%Y %H:%M:%S",dayfirst=True)>>>df
0 2013-12-28 19:23:15
dtype: datetime64[ns]
Solution 2:
In case you need to convert existing columns in a dataframe here the solution using a helper function conv
and the apply
method.
import datetime
import pandas as pd
defconv(x):
return datetime.datetime.strptime(x, '%d%b%Y %H:%M:%S')
series = pd.Series(['28Dec2013 19:23:15'])
converted = series.apply(conv)
02013-12-2819:23:15
dtype: datetime64[ns]
Solution 3:
Pandas does not recognize that datetime format.
>>>pd.to_datetime(Series(['28Dec2013 19:23:15']))
0 28Dec2013 19:23:15
dtype: object
>>>pd.to_datetime(Series(['28 Dec 2013 19:23:15']))
0 2013-12-28 19:23:15
dtype: datetime64[ns]
You will need to parse the strings you are feeding into the Series. Regular expressions will likely be a good solution for this.
Post a Comment for "In Python Pandas, How Can I Convert This Formatted Date String To Datetime"