Home > Net >  how can i filter data between two time i am using date time field for it in django rest framework
how can i filter data between two time i am using date time field for it in django rest framework

Time:05-15

I am trying to filter my data with a date-time field, but in my case its not working. So please someone suggest to me how can I filter my date with time

start_time = 2022-05-13 02:19:19.146009

end_time = 2022-05-13 02:20:19.146009

parser_order_mi = ParserOrderMenuItem.objects.filter(menu_item_id=menu_item_id,created_at__range=[start_time,end_end_time])

CodePudding user response:

You can use the __range(initial_time, end_time) approach:

start_time = 2022-05-13 02:19:19.146009
end_time = 2022-05-13 02:20:19.146009

ParserOrderMenuItem.objects.filter(timestamp__range=(start_time, end_time))

Or you can also use __gte that refers greater than or equal to and __lte that refers less than or equal to:

start_time = 2022-05-13 02:19:19.146009
end_time = 2022-05-13 02:20:19.146009

ParserOrderMenuItem.objects.filter(timestamp__gte=start_time,timestamp__lte=end_time)

CodePudding user response:

First, you need make sure which timezone your Django project is using. You can check this from TIME_ZONE variable in settings.py file. Let's say the timezone is UTC.

from datetime import datetime
import pytz

# assume that start_time and end_time is at your local timezone
inf_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")
sup_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S.%f")

# convert into UTC timezone
inf_time.astimezone(pytz.timezone("UTC"))
sup_time.astimezone(pytz.timezone("UTC"))

ParseOrderMenuItem.objects.filter(created_at__gte = inf_time).filter(created_at__lte = sup_time)

If you haven't installed pytz yet, then you can install it using the command pip install pytz. Hope it could you.

  • Related