This is driving me crazy. I've used all the lookup_types and none seem to work.
I need to select an object that was created two weeks ago from today.
Here's what I've got:
twoweeksago = datetime.datetime.now() - datetime.timedelta(days=14)
pastblast = Model.objects.filter(user=user, created=twoweeksago, done=False)
The model has a created field that does this: created = models.DateTimeField(auto_now_add=True, editable=False)
But my query isn't returning everything. Before you ask, yes, there are records in the db with the right date.
Can someone make a suggestion as to what I'm doing wrong?
Thanks
DateTimeField is very different from DateField, if you do
twoweeksago = datetime.datetime.now() - datetime.timedelta(days=14)
That is going to return today's date, hour, minute, second minus 14 days, and the result is going to include also hours minutes seconds etc. So the query:
pastblast = Model.objects.filter(user=user, created=twoweeksago, done=False)
Is going to find for a instance was created just in that exact time, If you only want to care about the day, and not hours, minutes and seconds you can do something like
pastblast = Model.objects.filter(user=user, created__year=twoweeksago.year, created__month=twoweeksago.month, created__day=twoweeksago.day, done=False)
Check the django docs:
https://docs.djangoproject.com/en/1.4/ref/models/querysets/#year
Related
I have a model and form with a TimeField and I want to make a change for the hour once the timefield is extracted from the form that was submitted and stored. I want to update the hour in the time. can anyone help me with this...
here is the view
start_time = cd['start_time']
hour = start_time.hour
new_hour = hour - int(alert)
update_time = start_time
update_time.hour = new_hour
update_time.save()
So the start_time is a timefield that submitted.
I want to grab the hour from that start time to change it. how can i do that...
this is the error essage I am getting:
attribute 'hour' of 'datetime.time' objects is not writable
I want to grab the hour from the original time and updated/change it
datetime instances are immutable, but there is a method to get a new instance with one (or serveral) of the fields replaced with a different value. It's documented here: https://docs.python.org/3/library/datetime.html#datetime.datetime.replace
So your example would become something like this:
start_time = cd['start_time']
update_time = start_time.replace(hour=start_time.hour - int(alert))
I'm not sure why you are calling save on update time. I'm assuming that's a mistake in your example.
I have field in my model:
class Order(BaseModel):
created_at = models.DateTimeField(auto_now_add=True)
I need to count all Order objects created in current month.
How can I do this in my views?
One of possible ways.
from datetime import datetime
current_month = datetime.now().month
Order.objects.filter(created_at__month=current_month)
See https://docs.djangoproject.com/en/stable/ref/models/querysets/#month for reference.
The (current) accepted answer is incorrect. As stated in comments, maybe OP wants current month in current year. Not current month in any year. Well most people want the first.
So I would rather do
Order.objects.filter(created_at__gte=timezone.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0))
The above also gets around timezone issues.
If you're only after the current month, it's easy, because you don't have to worry about an end date - nothing can be created after now, after all.
start_of_month = datetime.date.today().replace(day=1)
orders_this_month = Order.objects.filter(created_at__gte=start_of_month)
This worked best on my side by adding .count operation
import datetime
Order.objects.filter(created_at__gte=datetime.datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0)).count()
I want to compare a DateField and a TimeField in a queryset with the current date. I searched for hours but did not find anything. Tried much with Q/F-Object but no solution, too. And now I am here and hope someone knows how to solve this :) - Btw. splitting into date and time is not my fault and there is no way to change it into a DateTimeField (too much dependencies in other projects).
class Model(models.Model):
date = models.DateField()
time = models.TimeField()
In MySQL I would do something like:
SELECT * FROM app_model WHERE CAST(CONCAT(CAST(date as CHAR),' ',CAST(time as CHAR)) as DATETIME) >= NOW()
Thanks for any suggestions!
You can do this with or'd queryset contraints (Q objects):
now = datetime.datetime.now()
future_models = Model.objects.filter(Q(date__gt=now.date()) | (Q(date=now.date()) & Q(time__gte=now.time())))
That selects all instances for which date is past today, and all instances for which date is today and the the time is greater than or equal to the current time.
Hi I am writing a Django view which ouputs data for graphing on the client side (High Charts). The data is climate data with a given parameter recorded once per day.
My query is this:
format = '%Y-%m-%d'
sd = datetime.datetime.strptime(startdate, format)
ed = datetime.datetime.strptime(enddate, format)
data = Climate.objects.filter(recorded_on__range = (sd, ed)).order_by('recorded_on')
Now, as the range is increased the dataset obviously gets larger and this does not present well on the graph (aside from slowing things down considerably).
Is there an way to group my data as averages in time periods - specifically average for each month or average for each year?
I realize this could be done in SQL as mentioned here: django aggregation to lower resolution using grouping by a date range
But I would like to know if there is a handy way in Django itself.
Or is it perhaps better to modify the db directly and use a script to populate month and year fields from the timestamp?
Any help much appreciated.
Have you tried using django-qsstats-magic (https://github.com/kmike/django-qsstats-magic)?
It makes things very easy for charting, here is a timeseries example from their docs:
from django.contrib.auth.models import User
import datetime, qsstats
qs = User.objects.all()
qss = qsstats.QuerySetStats(qs, 'date_joined')
today = datetime.date.today()
seven_days_ago = today - datetime.timedelta(days=7)
time_series = qss.time_series(seven_days_ago, today)
print 'New users in the last 7 days: %s' % [t[1] for t in time_series]
Is there a method that I am not finding for getting the distinct hours in a DateTimeField? I essentially want the exact same thing that .dates() provides but for hours.
I should clarify that I am talking about a QuerySet method. The dates() method I am talking about is here:
http://docs.djangoproject.com/en/1.1/ref/models/querysets/#dates-field-kind-order-asc
If not, is there a recommended known solution?
Thanks.
Adding for clarification:
I have a model called Event with a DateTimeField called start_date. We need to know which hours of a particular day have an event.
Let's say that we narrow it down to a particular month:
objects = Event.objects.filter(start_date__year=2010, start_date__month=2)
Now the dates functions could give me a a list of all the days that have an event:
distinct_days = objects.dates('start_date', 'day')
What I would like is the narrow it down to a particular day, and then get a distinct list of the hours in the day that have an event.
objects = Event.objects.filter(start_date__year=2010, start_date__month=2, start_date__day=3)
distinct_hours = objects.times('start_date', 'hour') # This command doesn't exist and am wondering how to do this
Thanks.
Do you want to get the hours from a datetime object? Which .dates() do you mean?
hour = instance.yourDateTimeField.hour
Unfortunately there isn't a good way to do this at present, the best way is to use some raw SQL in conjunction with the extra() method and then call distinct().
I have created this code in order to manually do it.
hours = []
for h in objects.values('start_date'):
hours.append(h['start_date'].hour)
tempdict = {}
for x in hours:
tempdict[x] = x
hours = tempdict.values()
hours.sort()
Simple solution: hours might be stored in separate field, with unique=True.