0

I am writing a query to get duration between 2 date fields. One is from django model (dateField) and other is simply datetime.date.today(). I have used F() objects for model column value to avoid memory usage.

    def duration(self):
        emp_duration = Employee.objects.values('empName', 'empJoining').annotate(
            duration=(datetime.date.today() - F('empJoining'))
        )
        return HttpResponse(emp_duration)

Output:

{'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': -20028098.0}
{'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': -20218786.0}
{'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': -20218694.0}

Have a look at duration field. I don't understand why its in negative.

Then I used ExpressionWrapper with outputfield as DurationField(). Since F() objects needs ExpressionWrapper to define outputFields.

    def duration(self):
        emp_duration = Employee.objects.values('empName', 'empJoining').annotate(
            duration=ExpressionWrapper(
                (datetime.date.today() - F('empJoining')), output_field=DurationField()
            )
        )
        return HttpResponse(emp_duration)

Output:

{'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=971902)}
{'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781214)}
{'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781306)}

Days difference is same in each row and not the right answer though. The substraction is not correct. What is the issue, if someone can give me better approach or point out what am I missing here, that will be a favor.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • Which DBMS? Did you `print(datetime.date.today())` to check if your machine time is correct in the first place? – aaron Jan 31 '23 at 13:29
  • I couldn't reproduce this. – aaron Jan 31 '23 at 13:42
  • Its MySQL. Yes, I printed this. The date is correct. Let me know what code snippet is required, I will attach that also. – MeharunNisa Jan 31 '23 at 14:43
  • Can you log the SQL queries to see what's wrong? See [How to log all sql queries in Django?](https://stackoverflow.com/q/4375784/8601760). – aaron Feb 05 '23 at 12:42

0 Answers0