简体   繁体   English

在python pandas中,如何将此格式化的日期字符串转换为datetime

[英]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" 我已经尝试了几种使用to_datetime ,但到目前为止我只能将它作为“对象”返回to_datetime

pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),dayfirst=True)

The return from this command is: 该命令的返回值为:

0    28Dec2013 19:23:15
dtype: object

You can pass a format parameter to the to_datetime function. 您可以将format参数传递给to_datetime函数。

>>> 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]

In case you need to convert existing columns in a dataframe here the solution using a helper function conv and the apply method. 如果您需要在数据框中转换现有列,请使用辅助函数convapply方法。

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]

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. 正则表达式可能是一个很好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM