Philipp Zettl
Philipp Zettl

Reputation: 197

Django calculation with many TimeFields

I'm working on a webapp, which should calculate with several TimeField objects. No I stuck at one point. How is it possible to add different TimeFields together and subtract a DecimalField from the outcome TimeField. I've tried different ways. For example to convert the TimeFields into a str-object (which doesn't work either...). Does anyone of you got an idea how I can handle that issue? A small hint would be a pleasure for me. Thanks!

Upvotes: 0

Views: 109

Answers (1)

AKX
AKX

Reputation: 168834

What are you actually trying to do? :) I'll have to guess to begin with...

Remember TimeFields carry datetime.time objects, which are "clock time", i.e. from midnight to midnight. I'm assuming you want to convert them to a form that you can handle arithmetically -- seconds since midnight works fine for that.

I'm using raw datetime.time objects here for simplicity, but it's the same thing with Django's TimeFields.

import datetime, decimal

def to_seconds_after_midnight(t):
    return t.hour * 60 * 60 + t.minute * 60 + t.second + (t.microsecond / 1000000.)

hourly_fee = decimal.Decimal(90)  # for example.

time_1 = datetime.time(13, 15)
time_2 = datetime.time(16, 20)

second_interval = decimal.Decimal(
    to_seconds_after_midnight(time_2) -
    to_seconds_after_midnight(time_1)
)
print(hourly_fee * (second_interval / 60 / 60))  # The output is 277.5.

HTH :)

Upvotes: 1

Related Questions