2

When I try to calculate a time difference between two fields using F expression it results in TypeError. I can't understand what's the problem, especially because there are other examples where F expressions were used to do the same (here: Timedelta between two fields)

model:

class TimeStamp(models.Model):
   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

Expression:

q = TimeStamp.objects.all().annotate(diff=F('created_at')-F('updated_at'))

print(q)

and error reports (not a full report):

File "lib/python3.5/site-packages/django/utils/dateparse.py", line 93, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object

I use Django 1.8.8 if this matters.

Philipp Chapkovski
  • 1,949
  • 3
  • 22
  • 43

1 Answers1

2

Try to use ExpressionWrapper with DurationField:

from django.db.models import DurationField   
q = TimeStamp.objects.all().annotate(diff=ExpressionWrapper(F('created_at')-F('updated_at'), output_field=DurationField()))
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100