Search code examples
pythonpandasxlsx

unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'


Ca  Tên NVNL    Check in    Check out   Thời gian làm việc trong ca     Hỗ trợ ăn trưa
0   Ca Sáng     Ngô Hải Anh     08:15:00    12:13:00    NaN     NaN
1   Ca Chiều    Ngô Hải Anh     14:00:00    17:35:00    NaN     NaN
2   Ca Chiều    Ngô Văn Ninh    13:30:00    17:57:00    NaN     NaN
3   Ca Chiều    Nguyễn Hoàng Anh    14:00:00    17:43:00    NaN     NaN

I want to subtract Check out to Check In column. By this code

data['Thời gian làm việc']= data['Check out '] - data['Check in']

But i get this error: TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' Please help me.


Solution

  • I think here is possible convert values to timedeltas by to_timedelta, but first cast to strings:

    data['Thời gian làm việc']= (pd.to_timedelta(data['Check out'].astype(str)) - 
                                 pd.to_timedelta(data['Check in'].astype(str)))
    

    Or to datetimes by to_datetime:

    data['Thời gian làm việc']= (pd.to_datetime(data['Check out'].astype(str)) - 
                                 pd.to_datetime(data['Check in'].astype(str)))