Django.fun

Time Difference in Django Model

I am making a Django Software for a flight school to be made. I am trying to work on time difference between Arrival Time and Departure time to give me an Actual Elapsed Time. I post the code here:

Models

class LogEntry(models.Model):
aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE)
from_aerodrome = models.ForeignKey(
    Aerodrome, on_delete=models.PROTECT, related_name='from_aerodrome')
to_aerodrome = models.ForeignKey(
    Aerodrome, on_delete=models.PROTECT, related_name='to_aerodrome')
departure_time = models.TimeField()
arrival_time = models.TimeField()
pilot = models.ForeignKey(
    Pilot, on_delete=models.PROTECT, related_name='pilot')
instructor = models.ForeignKey(
    Pilot, on_delete=models.PROTECT, related_name='instructor', blank=True, null=True)
date = models.DateField(auto_now_add=True)
remarks = models.CharField(max_length=1000, blank=True, null=True)
eet = models.CharField(max_length=255)

@property
def get_eet(self):
    aet = self.arrival_time - self.departure_time
    return aet

def save(self, *args, **kwargs):
    self.eet = self.get_eet
    super(LogEntry, self).save(*args, **kwargs)

class Meta:
    ordering = ('-arrival_time',)
    verbose_name_plural = 'Log Entries'

Views:

def insert_flight(request):
aircraft = Aircraft.objects.all()
aerodrome = Aerodrome.objects.all()
pilot = Pilot.objects.all()

if request.method == 'POST':
    aircraft_id = request.POST.get('aircraft')
    from_aerodrome = request.POST.get('from_aerodrome')
    to_aerodrome = request.POST.get('to_aerodrome')
    departure_time = request.POST.get('departure_time')
    arrival_time = request.POST.get('arrival_time')
    pilot = request.POST.get('pilot')
    instructor = request.POST.get('instructor')

    log_entry = LogEntry(aircraft_id=aircraft_id, from_aerodrome_id=from_aerodrome, to_aerodrome_id=to_aerodrome,
                         departure_time=departure_time, arrival_time=arrival_time, pilot_id=pilot, instructor_id=instructor)
    log_entry.save()

context = {
    'aircraft': aircraft,
    'aerodrome': aerodrome,
    'pilot': pilot,
}
return render(request, 'flight/insert_flight.html', context)

The error I am getting is:

Error:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

What am I doing wrong? I tried to find a solution online but I couldn't find much information on "time handling issues" in Python.

Answers: 1

Answered by HIMANSHU KAWALE, Dec. 3, 2021, 3:05 p.m.

aet = self.arrival_time - self.departure_time Probably the issue is in this line.

self.arrival_time and self.departure_time are strings, you need to convert them to DateTime object. You can use datetime.strptime() from datetime module.

You can refer to the below code,

from datetime import datetime

arival_time = datetime.strptime(self.arival_time, '%d/%m/%y %H:%M:%S')
departure_time = datetime.strptime(self.departure_time, '%d/%m/%y %H:%M:%S')

aet = arrival_time - departure_time