我正在嘗試為我的網絡應用程序進行正確的日期處理設置.我有一個看起來像這樣的模型
class Entity(models.Model): name = models.CharField(max_length=255) date = models.DateTimeField()
用戶可以向我的DRF端點/ api / v1 / entity /發送請求以獲取此類實體的列表.現在要求用戶應該能夠在一天內請求所有Entity對象,這由date參數確定.日期以UTC格式存儲在數據庫中,而此應用的用戶不在UTC時區.
用戶可以創建具有以下日期2018-06-19T01:00:00 02:00的實體,該實體在數據庫中存儲為2018-06-18T23:00:00Z.現在,如果我嘗試列出用戶為2018-06-19創建的所有實體,則返回任何內容,但按2018-06-18過濾將返回一個條目.
這是我正在使用的代碼設置:
http://127.0.0.1:8000/api/v1/entity/?date=2018-06-18.
def get_queryset(self): user = self.request.user entities = Entity.objects.filter(owner=user) date = self.request.query_params.get('date') if date: entities = entities.filter(date__date=date) return entities
因此,在這種情況下,適當的日期范圍是2018-06-18T23:00:00Z – 2018-06-19T23:00:00Z.在用戶的時區中獲取一天(或日期范圍)的所有實體的正確方法是什么?
如果我理解正確,您必須將本地DateTime轉換為等效的UTC時間並查詢數據庫.所以我在下面定義了一個簡單的時間轉換函數
import pytz
from datetime import datetime def convert_to_UTC(local_tz,dt_1,dt_2): """ local_tz : any possible timezone which supports pytz lib (https://stackoverflow.com/questions/13866926/is-there-a-list-of-pytz-timezones) dt_1 and dt_2 : local datetime in string in this format ->> '%Y-%m-%dT%H:%M:%S' return a list as ->> [utc_equivalent_of_dt_1_in_string,utc_equivalent_of_dt_2_in_string] """ format='%Y-%m-%dT%H:%M:%S' pytz_local_tz = pytz.timezone(local_time_zone) dt_obj_from_date_time = datetime.strptime(dt_1,format) dt_obj_to_date_time = datetime.strptime(dt_2,format) return [pytz_local_tz.localize(dt_obj_from_date_time).astimezone(tz=pytz.utc).strftime(format), pytz_local_tz.localize(dt_obj_to_date_time).astimezone(tz=pytz.utc).strftime(format)]
要使用此功能,請更改get_queryset()方法,如下所示,
def get_queryset(self): user = self.request.user entities = Entity.objects.filter(owner=user) date_from = self.request.query_params.get('date_from') date_to = self.request.query_params.get('date_to') if date_from and date_to: entities = entities.filter(date__range=convert_to_UTC('Asia/Kolkata', date_from, date_to)) return entities
因此,網址將是,/ api / v1 / entity /?date_from = 2018-06-18T23:00:00& date_to = 2018-06-19T23:00:00