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

Python中使用strptime转换时间数据时遇到的问题

解决datetime.strptime格式不匹配的问题

问题根源

你遇到的错误核心原因很明确:stime_record里的每个元素都是单元素嵌套列表,而非直接的时间字符串。当你用str(x)转换时,得到的是类似"['01/01/2016 00h15m']"这种带括号、引号的字符串,完全不符合你指定的'%d/%m/%Y %Hh%Mm'格式,自然会触发格式不匹配的报错。

解决方案

只需要先提取每个嵌套列表里的字符串元素,再传入datetime.strptime即可。这里给你两种实用的处理方式:

方式1:循环内直接索引提取

遍历列表时,直接取子列表的第一个元素(索引0)来获取时间字符串:

import datetime

stime_record = [['01/01/2016 00h15m'], ['01/01/2016 00h48m'], ['01/01/2016 01h08m'], ['01/01/2016 03h06m'], ['01/01/2016 05h22m'], ['01/01/2016 08h34m'], ['01/01/2016 09h59m']]
datetime_list = []
for x in stime_record:
    # 提取嵌套列表中的时间字符串
    time_str = x[0]
    dt = datetime.strptime(time_str, '%d/%m/%Y %Hh%Mm')
    datetime_list.append(dt)

方式2:列表推导式简化代码

如果想让代码更简洁,可以用列表推导式一次性完成转换:

import datetime

stime_record = [['01/01/2016 00h15m'], ['01/01/2016 00h48m'], ['01/01/2016 01h08m'], ['01/01/2016 03h06m'], ['01/01/2016 05h22m'], ['01/01/2016 08h34m'], ['01/01/2016 09h59m']]
datetime_list = [datetime.strptime(x[0], '%d/%m/%Y %Hh%Mm') for x in stime_record]

延伸:计算平均时间差

转换出datetime对象列表后,就可以轻松计算相邻时间的平均差了:

# 计算所有相邻时间的差值
time_diffs = [datetime_list[i+1] - datetime_list[i] for i in range(len(datetime_list)-1)]
# 计算平均时间差
average_diff = sum(time_diffs, datetime.timedelta(0)) / len(time_diffs)
print(f"两点间平均时间差:{average_diff}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:33:01