In a django app ,I am sending a list of Entry
objects to the template.Each Entry
object has a start, end times which are datetime.time values(from TimeFields
on the form).While listing the Entry objects,I need to show the duration for each entry.Putting a duration field in model seemed to be reduntant since ,start and end times were already there
model
class Entry(models.Model):
title = models.CharField(unique=True,max_length=50)
starttime=models.TimeField(null=True)
endtime=models.TimeField(null=True)
...
template
{% for entry in object_list %}
<tr>
<td> {{entry.title}} </td>
<td> {{entry.starttime}}</td>
<td> {{entry.endtime}}</td>
<td> want to show duration here </td>
{%endfor %}
1.
Is there any filter which can take two datetime.time values and calculate the duration in seconds.
ie,
given
t1=datetime.time(2,30,50) and
t2=datetime.time(3,00,50)
should show
30 minutes
2.
Also,is there a filter,that can show a duration in given number of minutes as hour,minutes if the minutes value is greater than 60
ie,
if duration is 50 minutes ==> 50 minutes
if duration is 150 minutes ==> 2 hours,30 minutes
update
def diff_in_time(start,end):
startdelta=datetime.timedelta(hours=start.hour,minutes=start.minute,seconds=start.second)
enddelta=datetime.timedelta(hours=end.hour,minutes=end.minute,seconds=end.second)
return (enddelta-startdelta).seconds/60
when i tried with some sample time values ,it gave me the expected result
#start 11:35:00 pm
#end 00:05:00 am
start= datetime.time(23,35,00)
end = datetime.time(00,05,00)
print diff_in_time(start,end)
==> 30 minutes
#start 00:35:00 am
#end 01:35:00 am
start= datetime.time(00,35,00)
end = datetime.time(01,35,00)
print diff_in_time(start,end)
==>60 minutes
You've got a problem. You can't -- and shouldn't be able to -- compare two times. Is 11pm before or after 1am? It depends whether or not they're on the same day.
You need to either store them as datetime
or something else that represents a relatively absolute time, or you need to turn them into datetime
s like this:
def todatetime(time):
return datetime.datetime.today().replace(hour=time.hour, minute=time.minute, second=time.second,
microsecond=time.microsecond, tzinfo=time.tzinfo)
def timestodelta(starttime, endtime):
return todatetime(endtime) - todatetime(starttime)
This will fail to give the expected answer if the two calls to today
span midnight.
Then you should probably use this app for a DurationField which stores a timedelta
to store the result in the database for easy display.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With