0

models.py:

class Attendancename(models.Model):
    teacher_name = models.ForeignKey(Teachername)
    date = models.DateField('Date')
    intime = models.TimeField('IN-TIME')
    outtime = models.TimeField('OUT-TIME')
    def hours_conversion(self):
        tdelta = (datetime.datetime.combine(datetime.date.today(),self.outtime) - datetime.datetime.combine(datetime.date.today(),self.intime))
        res = float((tdelta).seconds/3600)
        return '{0:.2f}'.format(res,)

I used to define method inside my models class to calculate the time difference between 'intime' and 'outtime'. I also got succeed in it, but the results are not as I expect.

I have entered 'intime'-09:00 am and 'outime'-12:32 pm in my form field and it shows me 'total hours' - 3.54hr as output.

Can any body have any idea what's going wrong exactly? Thanks! in advance.

Gaurav Tomer
  • 721
  • 2
  • 9
  • 25

3 Answers3

0

output is the amount of hours to get in form of hours and minute

output = '{0:.2f}'.format(res,)
hours = output-(output%1)
minutes = (output%1)*60
return hours+":"+minutes

would be required

AlexanderRD
  • 2,069
  • 2
  • 11
  • 19
0

To get your output in the form of hh:mm (3:32), you need to access those attributes of the timedelta. Replace your return statement with the following.

hours, minutes = tdelta.seconds//3600, (tdelta.seconds//60)%60
return '{0}:{1}'.format(hours, minutes)
Brobin
  • 3,241
  • 2
  • 19
  • 35
0

If you don't mind seconds; you could just call str() function:

>>> from datetime import timedelta
>>> td = timedelta(hours=3, minutes=32)
>>> str(td)
'3:32:00'

You could drop seconds and microseconds:

>>> str(td).rpartition(':')[0]
'3:32'

Or you could format manually:

hours, seconds = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(seconds, 60)
print("%02d:%02d" % (hours, minutes))
# -> 03:32
jfs
  • 399,953
  • 195
  • 994
  • 1,670