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

datetime转datetime.time问题:提取datetime对象时间部分异常

提取datetime对象列表中的时间部分

你的问题出在使用strptime解析时间字符串——这个方法本身会生成包含日期的datetime对象,缺失日期时会自动补默认值(1900-01-01)。以下是两种直接解决的方案:

1. 获取datetime.time对象(推荐)

因为你的列表元素已经是datetime对象,无需转字符串再解析,直接调用对象的.time()方法即可提取纯时间部分:

import datetime

# 假设datetime_obj是你的datetime对象列表
time_list = [dt.time() for dt in datetime_obj]

输出结果类似13:32:00,属于datetime.time类型,保留时间结构,方便后续时间运算。

2. 获取时间字符串

如果只需要文本形式的时间,直接用strftime格式化datetime对象:

time_str_list = [dt.strftime('%H:%M:%S') for dt in datetime_obj]

得到的是['13:32:00', ...]这类字符串列表,适合直接展示。

内容的提问来源于stack exchange,提问作者Devendra Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:05:19