我正在提取数据时间并计算结果,但是00:00:00值以不同的方式显示。这是为什么 ?以及我该如何解决?”
我已经尝试将其读取为字符串,以获得char的子列表并转换为整数。”
Ts = datetime.timedelta(hours = 0, minutes = 0, seconds = 0)
for i in range(0,len(cell_sl)):
for item in cell_sl:
trans = item[i]
Ts = Ts + datetime.timedelta(
hours=int(str(trans[:2])),
minutes=int(str(trans[3:-3])),
seconds=int(str(trans[6:]))
)
print(Ts)
我希望输出例如是00:25:18,但是我得到了
TypeError: 'datetime.time' object is not subscriptable
答案 0 :(得分:1)
您的trans
或item
的值都是 datetime.time 对象的-这就是错误告诉您的内容:
TypeError:“ datetime.time”对象不可下标
您不能像f.e.那样对它们进行切片/下标。字符串:
trans = item[i] # <-- this is a "subscription" ... either item is a datetime Ts = Ts + datetime.timedelta(hours= int(str(trans[:2])), # or trans is one minutes= int(str(trans[3:-3])), seconds= int(str(trans[6:])))
使用datetime.time提供的时,分,秒属性:
Ts = Ts + datetime.timedelta(hours = trans.time.hour,
minutes = trans.time.minute,
seconds = trans.time.second)
如果不确定是哪种类型,请使用print(type(item))
查看其类型。
具有一个日期时间值的完整示例:
import datetime
Ts = datetime.timedelta(hours = 0, minutes = 0, seconds = 0)
print(Ts)
now = datetime.datetime.now()
Ts += datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second)
print(Ts)
输出:
0:00:00
10:24:17