0

I am having difficulty getting queryset results in my own timezone. for example: model field definition:

some_datetime_field= models.DateTimeField(null=True)

Query:

MyModel.values_list("some_datetime_field",flat=True).first()

returns

datetime.datetime(2019, 11, 5, 14, 56, 16, tzinfo=<UTC>)

instead of returning

datetime.datetime(2019, 11, 5, 6, 56, 16, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

I am working with python V3.7.5, Django V2.2.7 and PostgreSQL V12 as my database. In my setting I have:

TIME_ZONE = "America/Los_Angeles"
USE_TZ = True
USE_I18N = True
USE_L10N = True

From the documentation it says with regard to the "TIME_ZONE" settings: (https://docs.djangoproject.com/en/2.2/ref/settings/#time-zone)

When USE_TZ is True and the database supports time zones (e.g. PostgreSQL), it is an error to set this option.

so I tried to remove the TIME_ZONE from my setting:

USE_TZ = True
USE_I18N = True
USE_L10N = True

but that didnt work either, even worse, when I try to localize it with timezone.localtime(datetime_example) i get the time in Chicago time:

datetime.datetime(2019, 11, 5, 8, 56, 16, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>)

How can I get my query set to return DateTime in my chosen timezone instead of UTC?

jadeidev
  • 194
  • 3
  • 13
  • Keep `TIME_ZONE` (ignore the warning) and then check `timezone.localtime`. – heemayl Nov 18 '19 at 21:21
  • Yes, I have done that, but the queryset doesn't return the local timezone (as you can see in the first portion of the question with the TIME_ZONE setting). it only returns UTC. – jadeidev Nov 18 '19 at 21:30
  • It's saved and retrieved as UTC. You need to do the necessary conversions yourself. – heemayl Nov 18 '19 at 21:33
  • 1
    Please read https://stackoverflow.com/questions/33247854/return-datetimes-in-the-active-timezone-with-a-django-query. There is explanation for the similar case. – Ivan Markeev Nov 18 '19 at 21:36
  • 1
    Thank you @IvanMarkeev that was super helpful. I was looking for such a solution for a while. thank you for pointing this out. – jadeidev Nov 18 '19 at 21:55

0 Answers0