In python pandas, how can I convert this formatted date string to datetime

拜拜、爱过 提交于 2019-12-10 18:24:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!