Django calculation with many TimeFields
<p>I'm working on a webapp, which should calculate with several <code>TimeField</code> objects.
No I stuck at one point. How is it possible to add different <code>TimeFields</code> together and subtract a <code>DecimalField</code> from the outcome <code>TimeField</code>.
I've tried different ways. For example to convert the <code>TimeFields</code> into a <code>str-object</code> (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! </p>

<p>What are you <em>actually</em> trying to do? :) I'll have to guess to begin with...</p>

<p>Remember <code>TimeField</code>s carry <code>datetime.time</code> 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.</p>

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

<pre><code>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.
</code></pre>

<p>HTH :)</p>

python django