2

How to convert db DateTime field into local time and construct Q object for retrieving the dataset?

settings.py

LANGUAGE_CODE = 'en-us'
USER_TIME_ZONE = 'US/Pacific'
TIME_ZONE = 'UTC'
USE_TZ = True

models.py

class Hello(models.Model):

  lucky_day = models.DateTimeField()

One record in db (UTC format)

2019-02-03 03:02:45

filter.py

# Client browser is Pacific time without time, date only.
localtime_str = '2019-3-2' 

qset_filter = Q(lucky_day<to Pacific time from UTC>=localtime_str)
funnydman
  • 9,083
  • 4
  • 40
  • 55
user6101147
  • 185
  • 1
  • 3
  • 14
  • 1
    Why don't you convert the local time to UTC in Python rather than mucking around in the database (where the conversion of the db data would need to take place for filtering to work)? – Endre Both Apr 12 '19 at 06:24
  • That's not what I wanted as local time string has no time. Comparison will be invalid after conversion with db UTC time with time. I just want to compare date. Thanks. – user6101147 Apr 12 '19 at 16:56
  • 1
    Then look into the timezone conversion functions of your database and custom [Func](https://docs.djangoproject.com/en/2.2/ref/models/expressions/#func-expressions) expressions to harness them. – Endre Both Apr 12 '19 at 17:01

1 Answers1

-1

If you really want to first convert a utc datetime field to local datetime and then you want to filter based on localdatetime, you can use django aggregation to do that in this way:

YourModel.objects.annotate(new_local_datetime_field=convert_to_local_datetime('lucky_day')).filter(Q(new_local_datetime_field=some_other_datetime))

Reference to convert utc datetime to local datetime: Convert UTC datetime string to local datetime

reference to django annotation: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.annotate