Answer the question
In order to leave comments, you need to log in
Django - how to count the number of hours, minutes, seconds (TimeField)?
All good!
There is a model:
class Blablabla(models.Model):
start_t = models.TimeField(u"С", blank=True, null=True)
end_t = models.TimeField(u"По", blank=True, null=True)
Answer the question
In order to leave comments, you need to log in
If you need a universal solution for comparing any two fields containing time, then template tag is probably quite an adequate solution. If you only need to compare two specific fields of this model, it will be much easier for you to add the corresponding methods to the model and access them from the template ({{ blablabla_obj.hours }}, {{ blablabla_obj.minutes }}, {{ blablabla_obj.seconds }}).
However, your question is ill-posed. Do you really need to know the difference between these two values? In the form HH:MM:SS?
The author pointed out that minutes and seconds are not specified at all, and end_t is always greater than start_t. Thus, it is enough to compare start_t.hour and end_t.hour.
You can do this by adding the appropriate method to the model:
class Blablabla(models.Model):
start_t = models.TimeField(u"From", blank=True, null=True)
end_t = models.TimeField(u"To", blank=True, null=True)
def period_duration(self):
"""
Returns the length of the period between
start_t and end_t, in hours.
This is precise as long as both values
have 0 as minute/second.
"""
return self.end_t.hour - self.start_t.hour
class BlablablaTestCase(TestCase):
def setUp(self):
start_t = datetime.time(14)
end_t = datetime.time(18)
self.blablabla_obj = Blablabla.objects.create(
start_t=start_t,
end_t=end_t
)
def test_period_calculation(self):
"""
Tests that the period_duration method of the Blablabla
model correctly compares start_t and end_t.
"""
self.assertEqual(self.blablabla_obj.period_duration(), 4)
def tearDown(self):
self.blablabla_obj.delete()
def period_duration(self):
"""
Returns the length of the period between
start_t and end_t, in the following format:
HH:MM:SS
"""
total_seconds = (
(
self.end_t.hour*3600
+
self.end_t.minute*60
+
self.end_t.second
) - (
self.start_t.hour*3600
+
self.start_t.minute*60
+
self.start_t.second
)
)
hour, total_seconds = divmod(total_seconds, 3600)
minute, total_seconds = divmod(total_seconds, 60)
second = total_seconds
return "%02d:%02d:%02d" % (hour, minute, second)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question