计算员工工作时长报错:TypeError: datetime.time类型不支持减法操作
Hey there, let's sort out that error you're running into! The root issue is that Python's datetime.time objects don't support direct subtraction with the - operator—this arithmetic only works for datetime.datetime types. Below are two practical solutions to calculate your employees' shift working hours correctly:
Solution 1: Convert time columns to datetime objects
The easiest fix is to convert your Check in and Check out columns from datetime.time to datetime.datetime types, then compute the difference. Here's how to do it in pandas:
import pandas as pd # Convert time columns to datetime (pandas will auto-add a default date, e.g., 1900-01-01) data['Check in'] = pd.to_datetime(data['Check in'], format='%H:%M:%S') data['Check out'] = pd.to_datetime(data['Check out'], format='%H:%M:%S') # Calculate working duration data['Thời gian làm việc'] = data['Check out'] - data['Check in']
The result will be a timedelta object, which displays nicely as HH:MM:SS and can be further processed (e.g., extract total hours with .dt.total_seconds() / 3600 if you need numerical values).
If you want to explicitly use the current date instead of pandas' default, you can combine the time values with today's date:
from datetime import date data['Check in datetime'] = pd.to_datetime(str(date.today()) + ' ' + data['Check in'].astype(str)) data['Check out datetime'] = pd.to_datetime(str(date.today()) + ' ' + data['Check out'].astype(str)) data['Thời gian làm việc'] = data['Check out datetime'] - data['Check in datetime']
Solution 2: Calculate time difference manually (no type conversion)
If you prefer not to convert the column types, you can calculate the time difference by converting each time to total seconds, subtracting, then formatting back to HH:MM:SS:
def compute_time_diff(check_in, check_out): # Convert time to total seconds since midnight in_sec = check_in.hour * 3600 + check_in.minute * 60 + check_in.second out_sec = check_out.hour * 3600 + check_out.minute * 60 + check_out.second diff_sec = out_sec - in_sec # Convert back to HH:MM:SS format hours = diff_sec // 3600 minutes = (diff_sec % 3600) // 60 seconds = diff_sec % 60 return f"{hours}:{minutes:02d}:{seconds:02d}" # Apply the function to each row data['Thời gian làm việc'] = data.apply(lambda row: compute_time_diff(row['Check in'], row['Check out']), axis=1)
This gives you a string-formatted time difference. Just note that this won't handle overnight shifts (e.g., check-in at 22:00, check-out at 06:00 next day) automatically—you'd need to add logic to check if check_out is earlier than check_in and adjust the seconds accordingly.
内容的提问来源于stack exchange,提问作者Phuc Coi

