quba
quba

Reputation: 123

Django DateTime Subtraction Hours

I subtract two datetime objects and get integers instead of time in hours and minutes.

This is my MODEL.PY

class TimeLog(models.Model)
    start_date  = models.DateTimeField(null=True, blank=True, default=datetime.now)
    end_date    = models.DateTimeField(null=True, blank=True, default=datetime.now)
    time_diff = models.DateTimeField(null=True, blank=True)

TimeLog.objects.filter(time_diff=None).update(time_diff=F('end_date') - F('start_date'))

I get 2020-09-12 22:51:58.383288 - 2020-09-12 23:03:57.088453 = 718705165 How do I make 718705165 to be in hours and minutes?

Upvotes: 0

Views: 425

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You should make time_diff a DurationField [Django-doc] to specify a duration, not a date time object:

class TimeLog(models.Model):
    start_date  = models.DateTimeField(null=True, auto_now_add=True)
    end_date    = models.DateTimeField(null=True, auto_now_add=True)
    time_diff = models.DurationField(null=True, blank=True)

You can use an ExpressionWrapper [Django-doc] to convert it to a timedelta object:

from django.db.models import DurationField, ExpressionWrapper, F

TimeLog.objects.filter(time_diff=None).update(
    time_diff=ExpressionWrapper(
        F('end_date') - F('start_date'),
        output_field=DurationField()
    )
)

Upvotes: 1

Related Questions