Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

my models.py:

class Attendancename(models.Model):
    teacher_name = models.ForeignKey(Teachername, default='Ram')
    date = models.DateField('Date', default=datetime.datetime.today)
    intime = models.TimeField('IN-TIME', auto_now=True)
    outtime = models.TimeField('OUT-TIME', auto_now=True)

    def hours_conversion(self):
        startdelta = datetime.timedelta(hours=self.intime.hours, minutes=self.intime.minutes, seconds=self.intime.seconds)
        enddelta = datetime.timedelta(hours=self.outtime.hours, minutes=self.outtime.minutes, seconds=self.outtime.seconds)
        return (enddelta-startdelta).seconds/3600

    def __str__(self):
        return "%s" %self.teacher_name

my views.py:

def add_atten(request):
    if request.method == 'POST':
        form = AttendancenameForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('student:listatten'))
        else:
            print(form.errors)
    else:       
        form = AttendancenameForm()
    return render(request, 'add_atten.html', {'form': form},)

my forms.py:

class AttendancenameForm(ModelForm):
    intime = forms.TimeField(input_formats=('%H:%M',))
    outtime = forms.TimeField(input_formats=('%H:%M',))
    teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all())
    class Meta:
        model = Attendancename
        fields = ('teacher_name', 'date', 'intime', 'outtime',)

Actually I'm trying to calculate total number of hours based on difference of 'intime' and 'outtime' in my models.py file but it raises above erroe. I think I'm doing syntax error. Can anybody Please tell me what is the correct syntax or method to do so? Any body please suggest me what to do to fix it?

like image 997
Gaurav Tomer Avatar asked Jul 01 '15 08:07

Gaurav Tomer


People also ask

What is datetime datetime now () in Python?

Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.

How do you subtract hours and minutes in Python?

Subtract hours from given timestamp in python using relativedelta. In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has all the attributes to represent a duration i.e. Year, Month, Day, Hours, Minutes, Seconds and Microseconds.

How can you find the difference in time between two datetime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.


1 Answers

It's because you cannot subtract a datetime.time from a datetime.time. Convert them to datetime.datetime objects and it'll return a datetime.timedelta object that you could use.

If you're lucky enough to be using Django 1.8, they now have a DurationField that can be used.

Failing that, I would recommend converting the timedelta into either seconds or a floating point representation so you can actually store it to the database.

EDIT: Pulled up in comments for half arsing an answer.

For example - if you want to store the number of (integer) seconds, you can convert from a TimeDelta by using secs = td // timedelta(seconds=1).

like image 113
OldTinfoil Avatar answered Oct 05 '22 09:10

OldTinfoil