Is Django corrupting timezone-aware DateTimeField when saving it to the Database?

前端 未结 3 1813
耶瑟儿~
耶瑟儿~ 2021-01-16 08:08

I have a Django model as described here

I create and save an instance of this model:

>>> from django.db.models import Max, F, Func
>>&         


        
3条回答
  •  孤城傲影
    2021-01-16 08:51

    The primary difference between datetime and timestamp is that timestamp will automatically store a value as UTC, using the current mysql time_zone setting, and datetime will ignore the time_zone setting when inserting and retrieving records.

    You're using a datetime field, however you're also using the mysql UNIX_TIMESTAMP function against that field. When you do that, the docs explain that the server interprets the value as a local time value, based on the time_zone setting. This is the source of the conversion discrepancy.

    You have two choices.

    1. Ensure the time_zone session variable is set to UTC before running your query.
    2. Store the value into a timestamp field instead of a datetime field.

提交回复
热议问题