Home > Software design >  unable to substract two timefeild in django
unable to substract two timefeild in django

Time:01-06

Hi Team i have models as below. And i am trying to substract out time and in time .

class Attendance(models.Model):
   employee = models.ForeignKey(Employee, on_delete=models.CASCADE,
                                default=1, related_name='Attendance')
    attendance_date = models.DateField(null=True)
    in_time = models.TimeField(null=True)
    out_time = models.TimeField(null=True, blank=True)
    totaltime = models.TimeField(null=True, blank=True)

    def __str__(self):
        return str(self.employee)   '-'   str(self.attendance_date)

    @property
    def totaltime(self):
        FMT = '%H:%M:%S'
        currentDate = date.today().strftime('%Y-%m-%d')
        sub = datetime.strptime('out_time', FMT) -
            datetime.strptime('in_time', FMT)
        return sub

Still getting and error: ValueError: time data 'out_time' does not match format '%H:%M:%S'

Please advise what should i do ,I am expecting how i will substract two timefeild

CodePudding user response:

@property
def totaltime(self):
    total_time = datetime.timedelta(hours=self.out_time.hour, minutes=self.out_time.minute,
                                    seconds=self.out_time.second) - datetime.timedelta(hours=self.in_time.hour,
                                                                                      minutes=self.in_time.minute,
                                                                                      seconds=self.in_time.second)
    return total_time

CodePudding user response:

So, first, you are using total_time as a @property, so you can just drop the field. Second, you need to use timedelta to calculate the difference between times, which is where another problem arises, because it seems only to operate with datetime objects, so you must work around that:

models.py:

from datetime import datetime, date, timedelta

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE,
                                default=1, related_name='Attendance')
    attendance_date = models.DateField(null=True)
    in_time = models.TimeField(null=True)
    out_time = models.TimeField(null=True, blank=True)

    def __str__(self):
        return str(self.employee)   '-'   str(self.attendance_date)

    @property
    def total_time(self):
        total = ( datetime.combine(date.today(), self.out_time) - 
                  timedelta(
                        hours=self.in_time.hour, 
                        minutes=self.in_time.minute, 
                        seconds=self.in_time.second
                    ) 
                )
        return total.time()
  • Related