简体   繁体   中英

Django filter datetime with timezone field with date only

I have a field in django model: "created_at" which is datetime with timezone (example: 2022-08-09 14:03:18.467482+02). In my app, I have a form where user selects date only (example: 2022-06-09).

I'm trying to filter that field in my view like this:

res = MyObject.objects.all()
res = res.filter(created_at = date)

I'm getting the following error: RuntimeWarning: DateTimeField Mybject.created_at received a naive datetime (2022-06-09 00:00:00) while time zone support is active.

What is the best way to to filter my object with user input date? Do I need to add timezone to user selected date and how?

try adding .date() to Created_at it shoud convert the timezone object to date

Managed to solve this, the correct syntax is adding double underscore like this:

res = res.filter(created_at__date = date)

Datetime has the attributes created_at.date and created_at.time

res = MyObject.objects.all()
res = res.filter(created_at.date = date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM