I have a datetime field.
date = models.DateTimeField()
Im trying to do a query set for all the entries on that date and then order it by time. I get all the entries like this...
todays_entries = model.objects.filter(date__range=(start_date, end_date))
I understand if I wanted to order it by date i would add a order_by('date') method but the time is still all off in terms of the order...how can I go about ordering the time?
Related
I have tried very hard to understand how to update my data base, but struggling to even print out the value of the data returned.
My code in views.py:
#SET THE PLACEHOLDER DATE AND TIME AS A STRING AND CONVERT TO DATETIME
#QUERY THE DATA BASE TO FIND THE ROW WHERE END_END_TIME = PLACEHOLDER DATE AND TIME
#OUTPUT THE DATA TO THE TERMINAL
#UPDATE THE END_DATE_TIME TO CURRENT DATE AND TIME
date_time_placeholder = "2023-01-01 12:00:00"
datetime.strptime(date_time_placeholder, "%Y-%m-%d %H:%M:%S").date()
get_value = logTimes.objects.get(end_date_time = date_time_placeholder)
print(get_value)
The output:
logTimes object (155)
I can see in the admin site the code is working, it is finding the correct row, but I am not sure how to print the column data to the terminal instead of the just the object and ID.
What I am trying to achieve ultimately is to update the end_date_time in this row to the current date and time using datetime.now(), I am not having any success, not for the lack of trying for hours. Any help is appreciated.
You are getting the model object but not printing any of the model fields, which is why you are just seeing the object and ID. You can get the field by just printing get_value.end_date_time - if you then want to update it then you can do something like this, Django has a timezone module which I would recommend using:
from django.utils import timezone
get_value.end_date_time = timezone.now()
get_value.save()
I want to store time as unix timestamp in my MYSQL database, I have django project with model:
date = models.DateField()
But I didn't find any models.Timestamp()
or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.
In Django, one usually uses a DateTimeField [Django-doc] for that. It is a column that thus stores a combination of date and time.
One can let Django automatically intialize (or update) the timestamp if the record is constructed or updated with auto_now_add=True [Django-doc] to initialize it when the record was created, and auto_now=True [Django-doc] to update. So it is a common pattern to see a (base)model like:
class TimestampModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
such that subclasses of the TimestampModel thus have two extra columns created and updated that store the time when the object was created and last updated respectively.
A datetime column has a larger range, as is specified in the MySQL documentation:
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date
and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
In Django, I am trying to filter my query only to objects that were created before a certain hour in the day. I have a datetime field called 'created_at' that stored the datetime from which that object was created.
What I would like to do is:
query = query.filter(created_at__hour__lte=10)
Which I would expect to get all the objects that were created before 10am. However, when I try that I get a:
FieldError: Join on field 'created_at' not permitted. Did you misspell 'hour' for the lookup type?
I could loop through each day and get that day's objects, but that seems highly inefficient. Is there a way I can do this in a single query? If not, what is the fastest way to run this sort of filter?
__hour on a DateTimeField is a lookup type, so you can't mix it with another lookup type like __lte. You could construct a filter with Q objects, EG:
before_ten = Q(created_at__hour=0)
for hour in range(1, 11):
before_ten = before_ten | Q(created_at__hour=hour)
query = query.filter(before_ten)
If you can change your data model, it might be more convenient to save a creation time TimeField as well as your existing created_at.
In Django 1.9+, you can chain hour lookups like created_at__hour__lte, so the query from the question will work.
query = query.filter(created_at__hour__lte=10)
import datetime
start_time = datetime.datetime.now().replace(hour=00, minute=00)
certain_hour = 10
end_time = start_time.replace(hour=certain_hour)
query = query.filter(created_at__range=(start_time, end_time)
So my model is like this:
class Blog(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
And now I want to get the count of the blog posts by each month. The raw sql would look like:
SELECT COUNT (*), EXTRACT(MONTH FROM publication_date) AS month FROM blog GROUP BY month;
One solution I found is here, it suggests that getting a date list first then loop through it using filter for each iteration. I do not like it, I am looking for a way to get the result without using loop.
You could use something to the effect of Blog.objects.filter(publication_date__range=[start_of_month, end_of_month]) to get all items from between those two dates. See range for details.
I have a model with a datetime field:
class MyModel(models.Model):
created = models.DateTimeField(auto_now = True)
I want to get all the records created today.
I tried:
MyModel.objects.all().filter(created = timezone.now())
and
MyModel.objects.all().filter(created = timezone.now().date())
But always got an empty set. What is the correct way in Django to do this?
EDIT:
It looks strange, but a record, created today (06.04.2012 23:09:44) has date (2012-04-07 04:09:44) in the database. When I'm trying to edit it in the admin panel it looks correct (06.04.2012 23:09:44). Does Django handle it somehow?
Since somewhere in 2015:
YourModel.objects.filter(some_datetime__date=some_date)
i.e. __date after the datetime field.
https://code.djangoproject.com/ticket/9596
There may be a more proper solution, but a quick workup suggests that this would work:
from datetime import timedelta
start_date = timezone.now().date()
end_date = start_date + timedelta( days=1 )
Entry.objects.filter(created__range=(start_date, end_date))
I'm assuming timezone is a datetime-like object.
The important thing is that you're storing an exact time, down to the millisecond, and you're comparing it to something that only has accuracy to the day. Rather than toss the hours, minutes, and seconds, django/python defaults them to 0. So if your record is createed at 2011-4-6T06:34:14am, then it compares 2011-4-6T:06:34:14am to 2011-4-6T00:00:00, not 2011-4-6 (from created date) to 2011-4-6 ( from timezone.now().date() ). Helpful?
Try this
from datetime import datetime
now=datetime.now()
YourModel.objects.filter(datetime_published=datetime(now.year, now.month, now.day))