Opened 6 years ago

Closed 6 years ago

#29726 closed Bug (invalid)

Setting the Shanghai time zone causes a query error

Reported by: AberSheeran Owned by: nobody
Component: Database layer (models, ORM) Version: 2.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a little website. It's settings.py like this

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True

And then, I had saved some data in SQLite3. But get a error

>>> for each in Message.objects.all():
...     print(each.create_time.year, each.create_time.month)
... 
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
2018 8
>>> for each in Message.objects.filter(create_time__year="2018", create_time__month="09"):
...     print(each.create_time.year, each.create_time.month)
... 
2018 8
2018 8
2018 8
>>> 

These three messages were sent in the last eight hours of August 31, 2018 UTC. The result of querying through .all() is UTC time. But the result of querying through .filter() is Asia/Shanghai time. This brings me some trouble...

Change History (1)

comment:1 by Carlton Gibson, 6 years ago

Resolution: invalid
Status: newclosed

These three messages were sent in the last eight hours of August 31, 2018 UTC.

You're not showing the tzinfo for your Message objects' create_time, but they should be being stored as UTC.

From the Time zones docs:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

Try:

>>> m = Message.objects.first()
>>> m.create_time.tzinfo
<UTC>     # Is this the return? 

If so then this is correct behaviour. Asia/Shanghai is UTC+8, so the default time zone active (which is the time zone defined by the TIME_ZONE setting) those messages (created in the last 8 hours of Aug 31) are correctly fetched by your filter.

Review the time zone doc linked above. They tell you how to set the active timezone which will enable you to control the filtering behaviour in the way you expect. (See particularly Setting the current time zone.

Note: See TracTickets for help on using tickets.
Back to Top