Django queryset time interval - python

I need to make object selections in my database by time interval
currently i found a method to select only objects from a day but not from an interval with this:
data.filter(end_at__day=datetime.datetime.now().day)
I saw this on the django __gte documentation which means from a date until today but I failed to make it work
I have try this:
if request.method == 'POST':
form = DashboardSettingsForm(data=request.POST)
if form.is_valid():
dis_planned = form.cleaned_data.get('display_planned')
dis_currently = form.cleaned_data.get('display_currently')
dis_ended = form.cleaned_data.get('display_ended')
end_at = start_at = datetime.now()
if dis_ended:
end_at = datetime.now() - timedelta(hours=12)
if dis_planned:
start_at = datetime.now() + timedelta(hours=12)
data = data.filter(start_at__gt=start_at, end_at__gt=end_at)
print(f"interval: start{start_at} end{end_at}")

data = data.filter(start_at__gt=start_at, end_at__gt=end_at)
The above line means the objects need to satisfy:
start_ats that are later than datetime.now() - timedelta(hours=12)
end_ats that are later than datetime.now() + timedelta(hours=12)
So you need to use the reverse (lt) for end_at, to make it a filter that covers a range within:
data = data.filter(start_at__gt=start_at, end_at__lt=end_at)
This essentially means the objects need to meet this criteria:
start_ats that are later than datetime.now() - timedelta(hours=12)
end_ats that are earlier than datetime.now() + timedelta(hours=12)

Related

How to modify if-else logic to in a script to retrieve data for T-14 days

I have an exsting script which is used to extract data for T and T-1 day. I tried to modify it extract two weeks data, but the script is not able to search the dates other than current date
Check the code section :
def parse_gov():
reject_patterns = generate_reject_patterns()
today_str = date.today().strftime('%Y.%m.%d')
yesterday = date.today() - timedelta(days=14)
yesterday_str = yesterday.strftime('%Y.%m.%d')
#query_date = date.today()
#query_date = yesterday
query_last = '''select last sym, last source, last lastTimeStamp, last objectName...
query_all = '''select objectName, IONrecType, sym, source, lastTimeStamp, objectName, ....
def query(q, query_date):
if query_date = date.today() - timedelta(days=14):
date_clause = "date <= {date}, ".format(date = query_date)
kdbport = '1000' ( historical database)
else:
date_clause = ""
kdbport = '1001' (current database)
Your else part is not triggering because the comparison is not happening over there.
you need to change
query_date = date.today() - timedelta(days=14):
to
query_date == (date.today() - timedelta(days=14)):
You always use == for comparison, = will assign the value to the variable.

Check if any date in a range is between another range

I have the following situation:
This is my views.py:
def home(request):
date = datetime.date.today()
start_week = date - datetime.timedelta(date.weekday() + 1)
end_week = start_week + datetime.timedelta(6)
week_tasks = Task.object.filter(owner=request.user, start_date__range=[start_week, end_week])
context = {}
context['week_tasks'] = week_tasks
return render(request, 'home.html', context)
This view check if the start_date (DateField) is inside the range of the current week. But I have another field on the database, end_date, and I want to check if any value of this range is on the current week.
Check the exemple:
Let's supose that the current week is the week of the day 17. With my current view, only the All Day Event and Conference belong to the week. I need to show that all these events belong to the week.
Obs.: I can't just check if start_date and end_date are in the week, because I have the situation of the Long Event, that starts before the week and ends after.
WORKING:
views.py:
def home(request):
date = datetime.date.today()
if date.isoweekday() == 7:
date = date + datetime.timedelta(1)
start_week = date - datetime.timedelta(date.isoweekday())
end_week = start_week + datetime.timedelta(6)
week_tasks = Task.object.filter(owner=request.user).exclude(end_date__lt=start_week).exclude(start_date__gt=end_week)
context = {}
context['week_tasks'] = week_tasks
return render(request, 'home.html', context)
week window is defined by: week_start, week_end
tasks are defined by: task_start, task_end
task has overlap with week if:
task_start < week_end and task_end >= week_start

how to remove if end date is expired in python google app engine

My gql model is
start_date = db.DateTimeProperty()
end_date = db.DateTimeProperty()
my class is
class GetHandler(BaseHandler):
def get(self):
promos = Promotion.all()
self.render_response("/admin/promotion/index.html", promos=promos)
if end_date is expired [end_date<datetime.now] it should remove from my admin panel.
Based on Tim 's answer:
now = datetime.now() # get current datetime
q = db.Query(Promotion)
q = q.filter('end_date <', now)
for promo in q.run(): # loop over filtered promos
promo.delete() # delete instance from datastore
The documentation discourages the use of fetch instead of run. And it's probably a bad idea to fetch all the promos.
Compare the dates and act accordingly
promos = Promotion.all().fetch() # fetch all promos
now = datetime.now() # get current datetime
for promo in promos: # loop over all promos
if promo.end_date > now: # compare promo date to 'now'
promo.delete() # delete instance from datastore
comparing date(time)s is as simple as using > or <

All posts from same day only django

I currently have:
#classmethod
def get_past_week(self):
start_date = datetime.now().date()
end_date = datetime.now().date() - timedelta(weeks=1)
return MyModel.objects.filter(pub_date__range=(end_date, start_date)).aggregate(Sum('off_hours'))
which simply pulls all posts from the current date minus 7 days
I want to pull posts from within the same day factoring in the time at the moment. Thus if the time is 15:00 GMT now, I want all posts from 14:59:49 GMT back to 00:00:01 GMT of the same day. How can I do something like that?
I've tried something like (not work
def get_today_hours(self):
start_time = datetime.now().time()
end_time = datetime.now().time() - timedelta(hours=datetime.today().hour, minutes=0, seconds=0)
return MyModel.objects.filter(pub_date__range=(end_time, start_time))
According to this post on SO, there's a way to get items from same day by using CURDATE()
You can do the following
end_time = datetime.now()
start_time = datetime(end_time.year,end_time.month,end_time.day)
That will set end_time to actual time, and start_time to the same day as end_time, but with the time at 0 hours and 0 seconds.
How about this:
from datetime import datetime, timedelta
end_time = datetime.now()
start_time = datetime.combine(end_time, datetime.min.time()) #Reset the hours/time offset
qs = MyModel.objects.filter(pub_date__range=(start_time, end_time))
Or something even simpler:
qs = MyModel.objects.filter(pub_date__startswith=end_time.date())

Django quering objects with timestamp delta

Say I have a model:
Mymodel(models.Model):
endtimestamp = models.DateTimeField(null=True)
I need a query to get all Mymodel objects with endstimestamp between today's midnight and yesterday midnight.
what have I tried:
today = datetime.datetime.today()
todays_midnigh = datetime.datetime.fromtimestamp(
today.strftime('%Y-%m-%d 00:00:00.0')
)
yesterday_midnight = todays_midnight - datetime.timedelta(days=1)
objs = Mymodel.objects.filter(endtimestamp__range(
yesterday_midnight, todays_midnight)
)
But this line todays_midnigh = datetime.datetime.fromtimestamp(today.strftime('%Y-%m-%d 00:00:00.0')) does not work, and I know there must be a much pythonic and clear way of achieving this.
assumming this from datetime import datetime as dt, do that:
today = dt.today()
todays_midnigh = dt.combine(today,dt.max.time())
or
todays_midnigh = dt.combine(today,dt.min.time())
as appropriate

Categories