python – 在Pandas如何将一个字符串的日期字符串转换为datetime对象,并将它们放在一个DataFrame?

import pandas as pd
date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')

a = pd.Series(range(4),index = (range(4)))

for idx, date in enumerate(date_stngs):
    a[idx]= pd.to_datetime(date)

此代码位产生错误:

TypeError:” ‘int’ object is not iterable”

任何人都可以告诉我如何获取这一系列的日期时间字符串到DataFrame作为DateTime对象?

最佳答案
>>> import pandas as pd
>>> date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
>>> a = pd.Series([pd.to_datetime(date) for date in date_stngs])
>>> a
0    2008-12-20 00:00:00
1    2008-12-21 00:00:00
2    2008-12-22 00:00:00
3    2008-12-23 00:00:00

更新

使用pandas.to_datetime(pd.Series(..))。它简洁,比上面的代码快得多。

>>> pd.to_datetime(pd.Series(date_stngs))
0   2008-12-20 00:00:00
1   2008-12-21 00:00:00
2   2008-12-22 00:00:00
3   2008-12-23 00:00:00

转载注明原文:python – 在Pandas如何将一个字符串的日期字符串转换为datetime对象,并将它们放在一个DataFrame? - 代码日志