簡單的問題描述:
1. Django后台配置的上海時間
2. postgresql采用了默認UTC時間
3. 后台跟數據庫差了8個小時,頁面顯示沒得問題
4. 當通過orm執行原生SQL的時候發現按照小時統計的結果還是晚了八個小時
網上找了很多教程,有讓改postgresql配置文件,timezone改為PRC。改完之后數據庫顯示沒問題。但是通過SQL分組查詢還是會有問題
SELECT (to_char(take_photo_time, 'yyyy-mm-dd:HH')) AS "take_photo_time", COUNT(take_photo_time) AS "count" FROM "device_devicephotomodel" WHERE "device_devicephotomodel".take_photo_time BETWEEN '2020-12-23T00:00:00' :: TIMESTAMP AND '2020-12-24T00:00:00' :: TIMESTAMP GROUP BY (to_char(take_photo_time, 'yyyy-mm-dd:HH')) ORDER BY "take_photo_time" DESC;
統計到的結果,依然是晚了8個小時

通過date_trunte可以解決。但是還得調整接口,太麻煩
SELECT DATE_TRUNC( 'HOUR', take_photo_time ) AS "take_photo_time", COUNT ( take_photo_time ) AS "count" FROM "device_devicephotomodel" WHERE "device_devicephotomodel".take_photo_time BETWEEN '2020-12-23T00:00:00' :: TIMESTAMP AND '2020-12-24T00:00:00' :: TIMESTAMP GROUP BY ( DATE_TRUNC('HOUR', take_photo_time)) ORDER BY "take_photo_time" DESC;
於是找了一些比較官方的文檔,說是需要·····················。。直接貼解決方式
SELECT (to_char(take_photo_time, 'yyyy-mm-dd:HH24')) AS "take_photo_time", COUNT(take_photo_time) AS "count" FROM "device_devicephotomodel" WHERE "device_devicephotomodel".take_photo_time BETWEEN '2020-12-23T00:00:00' :: TIMESTAMP AND '2020-12-24T00:00:00' :: TIMESTAMP GROUP BY (to_char(take_photo_time, 'yyyy-mm-dd:HH24')) ORDER BY "take_photo_time" DESC;
上邊飄紅的地方,就是重點。兩個數字解決了一天·····有點無語

最后發現。正確了。滿足我的需求了。。可以回家了
