如何将pd.Series转换为datetime?

时间:2017-03-04 11:26:19

标签: python pandas numpy

我的环境:python3.6_x64,pandas 0.17.0,numpy 1.12.0

代码:

>>> import pandas as pd
>>> import numpy as np
>>> df_date = pd.Series(['2017-3-1','2017-3-2'])
>>> df_date
0    2017-3-1
1    2017-3-2
>>> pd.to_datetime(df_date)

错误:

ValueError: Error parsing datetime string "2017-3-1" at position 5
...
SystemError: <class 'str'> returned a result with an error set

3 个答案:

答案 0 :(得分:0)

使用known issue时,pandas中的Python 3.6看起来很多pandas version 0.19.2

In [12]: pd.Timestamp('invalid')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
ValueError: Error parsing datetime string "invalid" at position 0 

The above exception was the direct cause of the following exception:

SystemError                               Traceback (most recent call last)
<ipython-input-12-91abde127db1> in <module>()
----> 1 pd.Timestamp('invalid')
pandas/tslib.pyx in pandas.tslib.Timestamp.__new__ (pandas/tslib.c:9932)()
pandas/tslib.pyx in pandas.tslib.convert_to_tsobject (pandas/tslib.c:25231)()
pandas/tslib.pyx in pandas.tslib.convert_str_to_tsobject (pandas/tslib.c:26851)()
pandas/src/datetime.pxd in datetime._string_to_dts (pandas/tslib.c:87106)()
SystemError: <class 'str'> returned a result with an error set

答案 1 :(得分:0)

如果您仍需要日期时间列,请考虑将您的pandas Series对象转换为简单的DataFrame对象,然后将该列转换为datetime。

答案 2 :(得分:0)

我的环境:熊猫(0.18.1),numpy(1.12.1),Python 3.6.1(默认,2017年4月18日,01:19:53)

我使用相同的代码,但没有错误。 我的输出是这样的:

>>> import pandas as pd
>>> import numpy as np
>>> df_date = pd.Series(['2017-3-1','2017-3-2'])
>>> pd.to_datetime(df_date)
0   2017-03-01
1   2017-03-02
dtype: datetime64[ns]