首页 > 解决方案 > Python:将索引的数据类型从对象更改为日期时间会删除时间(HH:MM:SS)

问题描述

我正在尝试从每天到每小时对我拥有的一些数据进行上采样。为此,我需要获取日期时间格式的索引,但由于以下问题,我陷入了困境。

我将我的 df 加载到:

df1 = pd.read_csv("DATA.CSV", index_col="DT")
df1.head(5)

df1 示例

这看起来不错,但数据类型是对象,我需要转换为日期时间。所以我尝试了:

df1.index = pd.to_datetime(df1.index)
df1.head(5)

哪个确实可以更改数据类型,但索引现在已经失去了它的时间部分:

更改数据类型后的df1

有人能建议我如何制作数据类型日期时间并显示时间吗?有谁知道为什么时间会消失?可能是因为现在是 00:00:00?

标签: pythonpandas

解决方案


read the file as :

df1 = pd.read_csv("DATA.CSV")

then apply:

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d %H:%M:%S')
df.set_index('Date')

replace Date column with the original date column name.

Note: this converts the index to string.

Another solution:

df1 = pd.read_csv("DATA.CSV", index_col="DT", parse_dates=['DT'])
df1.index = df1.index.strftime('%Y-%m-%d %H:%M:%S')

推荐阅读