I’m working with two Time fields in my custom Frappe Doctype:
from_time (e.g., 09:00)
time (e.g., 17:30)
I want to calculate the total working hours between these two time fields (not just the time difference in terms of string/duration, but the actual hours as a float like 8.5).
I’ve seen frappe.utils, but I’m not sure which is the correct utility function to use specifically for Time fields (not Datetime).
3 Likes
Since you’re dealing with Time fields (not DateTime), you won’t find a direct frappe utility just for that. Best practice is to use Python’s datetime and timedelta together with Frappe’s get_time helper.
Here’s a clean way to do it inside your Doctype Python code (e.g., validate or a custom method):
from frappe.utils import get_time
def calculate_hours(from_time, to_time):
# convert to Python time objects
start = get_time(from_time)
end = get_time(to_time)
# convert to datetime for subtraction
from datetime import datetime, timedelta
today = datetime.today().date()
dt_start = datetime.combine(today, start)
dt_end = datetime.combine(today, end)
# handle case where end < start (e.g., crossing midnight)
if dt_end < dt_start:
dt_end += timedelta(days=1)
diff = dt_end - dt_start
hours = diff.total_seconds() / 3600 # float hours
return hours
Usage inside your DocType:
self.total_hours = calculate_hours(self.from_time, self.time)
Example:
- from_time =
09:00
- time =
17:30
→ hours = 8.5
Key point: frappe.utils.get_time() converts a Time field to a Python time object safely, then you do the math with datetime.combine.