字符串日期到目前为止(熊猫)

时间:2015-09-29 13:33:20

标签: python pandas

我有一个名为dfactual的数据框,此数据框有一列ForeCastEndDate,所以

dfactual['ForeCastEndDate'] it contains:

   311205
   311205

这必须是格式为31-12-2005的日期,但当前格式为int64。我尝试了以下方法:

dfactual['ForeCastEndDate'] = pd.to_datetime(pd.Series(dfactual['ForecastEndDate']))

我还尝试将format命令添加到它,但它没有解决格式保持不变的问题,int64。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您不能将to_datetime与非str的dtypes一起使用,因此您需要先使用astype转换dtype,然后才能使用to_datetime和传递格式字符串:

In [154]:
df = pd.DataFrame({'ForecastEndDate':[311205]})
pd.to_datetime(df['ForecastEndDate'].astype(str), format='%d%m%y')

Out[154]:
0   2005-12-31
Name: ForecastEndDate, dtype: datetime64[ns]