You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pd.to_datetime将DataFrame的time列仅保留时间格式(无日期)

解决Pandas索引仅保留时分秒格式的问题

我来帮你搞定这个问题!你遇到的情况是pd.to_datetime在转换时间字符串时,默认会自动补充日期信息,导致索引带上了完整的日期时间。要只保留时分秒格式,可以通过以下两种方式实现:

方法一:提取datetime对象的时间部分(推荐)

利用Pandas的.dt.time属性,从转换后的datetime对象中单独提取时分秒部分作为索引,这种方式保留了时间类型的特性,方便后续进行时间相关的操作:

import pandas as pd
import tushare as ts

# 获取目标数据
data = ts.get_tick_data('600030', date='2019-06-28', src='tt')[['time','price','change','volume','amount']]
# 转换为datetime后提取时分秒作为索引
data.index = pd.to_datetime(data['time']).dt.time
# 删除原time列
del data['time']

print(data.head())

运行后你的索引就会变成类似09:25:04的纯时分秒格式,且索引类型为datetime.time,支持时间排序、区间筛选等操作。

方法二:直接使用字符串作为索引

如果你不需要时间类型的特性,也可以直接将原time列的字符串值作为索引,省去转换步骤:

import pandas as pd
import tushare as ts

data = ts.get_tick_data('600030', date='2019-06-28', src='tt')[['time','price','change','volume','amount']]
# 直接将time列设为索引
data.set_index('time', inplace=True)

print(data.head())

这种方式的索引是字符串类型,虽然格式符合要求,但在进行时间相关的逻辑处理时不如datetime.time灵活。

内容的提问来源于stack exchange,提问作者XY XUE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:28:57