Search code examples
pythonexcelpython-datetime

How to fix "'TypeError: datetime.time' object is not subscriptable"


I'm working on extracting data time and calculating there results but 00:00:00 values display in a different manner. Why is that ? and how can i fix it?"

I have already tried to read it as a string get a sublist of char and converted to a integer."

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)

I expect the output to be for example 00:25:18, but I get TypeError: 'datetime.time' object is not subscriptable


Solution

  • Either your trans or your item values are datetime.time object's - thats what the error tells you:

    TypeError: 'datetime.time' object is not subscriptable

    You cannot slice/subscript them like f.e. strings:

    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:])))
    

    Use the hour, minute, second attributes provided by datetime.time instead:

    Ts = Ts + datetime.timedelta(hours = trans.time.hour, 
                                 minutes = trans.time.minute, 
                                 seconds = trans.time.second)
    

    If you are unsure which one is it, use print(type(item)) to see what type it is.


    Full example with one datetime value:

    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)
    

    Output:

    0:00:00
    10:24:17