问题
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)
The return from this command is:
0 28Dec2013 19:23:15
dtype: object
回答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]
回答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
def conv(x):
return datetime.datetime.strptime(x, '%d%b%Y %H:%M:%S')
series = pd.Series(['28Dec2013 19:23:15'])
converted = series.apply(conv)
0 2013-12-28 19:23:15
dtype: datetime64[ns]
回答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.
来源:https://stackoverflow.com/questions/31973895/in-python-pandas-how-can-i-convert-this-formatted-date-string-to-datetime