Get all objects with today date, django - python

I have a model like this
class Maca(models.Model):
created_at = models.DateTimeField(
auto_now_add=True
)
Now I want in the views.py file to get all the entries that have created today,
I'm trying this
Maca.objects.filter(created_at=datetime.today().date())
But this looks for the clock that object is created too.
P.S I can't change the field in model because I need the clock too in other purposes.
Can someone help me to select all entries that have been created today?
Thanks in advance

You have to just write a valid filter like this :
from datetime import datetime
today = datetime.today()
year = today.year
month = today.month
day = today.day
meca = Meca.objects.filter(created_at__year=year,
created_at__month=month, created_at__day=day)

I think the main reason is because you trying to compare dt field with date.
You can use prefixes for a field.
Or you can compare your 'today' value as dt(just an example):
today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
records = Maca.objects.filter(created_at >= today)

there many ways to get today data from database.
year = datetime.datetime.now().strftime('%y')
month = datetime.datetime.now().strftime('%m')
day = datetime.datetime.now().strftime('%d')
filtereddata = Maca.objects.filter(created_at__year=year,created_at__month=month, created_at__day=day )
the second way is to filter with contains
filtereddata = Maca.objects.filter(created_at__contains=datetime.today().date())
if datetime.datetime not work. just remove one datetime only use single datetime

Related

How to filter objects in Django by time since last 24 hours?

Assuming there's a starting time from 00:00 to 00:00 every day, how best are Django objects filtered by time, based on the current day? I initially came up with this:
from django.utils import timezone
yesterday = timezone.now() - timezone.timedelta(1)
qs = Foo.objects.filter(date__gte=yesterday)
##
yesterday = datetime.date.today() - datetime.timedelta(1)
qs = Foo.objects.filter(date__gte=yesterday)
However, this is not particularly right. I would prefer time starting exactly from 00:00 to timezone.now() -so something like Foo.objects.filter(date__range=[00:00, timezone.now()]) Thank you.
Assuming date field is actually a datetime.
If you need all records with date containing todays date, you can use __date:
qs = Foo.objects.filter(date__date=timezone.now())
If you need, for example, all yesterdays records, but with time not greater than timezone.now(), this way:
qs = Foo.objects.filter(
date__date=timezone.now() - timezone.timedelta(1),
date__lte=timezone.now() - timezone.timedelta(1)
)
Yevgeniy Kosmak's answer is correct, use datetime_field__date= filter.
Here are the Django docs
Also you can use date/datetime - timedelta() pattern with others arguments in timedelta, like
timedelta(
days=50,
seconds=27,
microseconds=10,
milliseconds=29000,
minutes=5,
hours=8,
weeks=2
)
docs are here

How to filter date According to Today Current Date in Django?

I am trying to filter date in Django according to current date, But it's displaying mr 0 results, Please let me know Where I am mistaking.
Hers is my models.py file...
class Customer(models.Model):
name = models.CharField(null=True, blannk=True)
customer_date = models.DateTimeField(null=True, blannk=True)
here is my views.py file, where i am trying to get date according to today date...
from datetime import datetime, timedelta, time, date
def getdate(request):
today=datetime.today()
customer_data = Customer.objects.filter(customer_date=today).count()
print(customer_data, "Count Values")
I see some issue in your date filter. When you do:
datetime.datetime.today()
#2020-11-04 10:57:22.214606
this give complete timestamp.
However you want to do date match only.so, try something like code.
today = datetime.today().date()
#today=datetime.today()
customer_data = Customer.objects.filter(customer_date__date=today).count()
hope this may help your query.
I saw you mistyped blank as blannk

django queryset filter with datetime and date

I have a queryste:
winner_check = Winner.objects.filter(win_date=date.today())
where win_date is datetime and date.today() gives only date... Is there anyway that I can convert win_date to only date and filter this queryset.
I want to filter all the winners which have same date.
Thanks in advance.
You can't. But you can create range from 2 datetimes and filter your queryset by it. Also you can separately filter by win_date__year, win_date__month and win_date__day.
You can filter using __year, __month and __day:
today = date.today()
Winner.objects.filter(win_date__year=today.year,
win_date__month=today.month,
win_date__day=today.day)
docs
The most efficient way is to use the __range lookup between two datetimes or the combination of __gte/__lt lookups for today/tomorrow dates:
import datetime
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
winner_check = Winner.objects.filter(win_date__gte=today,
win_date__lt=tomorrow)
This will lead to filtering the win_date from TODAY 0:00:00 to TODAY 23:59:59

Using .filter to show DB entries created (today) in Django

My form allows users to create entries into the database and is timestamped with:
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
This creates entries like: 2015-02-20 03:10:00
How can I use the .filter to search just the day part of the timestamp? I have so far:
for running in viewteam.daily_risk_set.all().filter(team = 4713).filter(created = today).order_by('-created')[:1]:
// do something
I am looking to show just the last entry for team 4713 but I do not know how to work with the dates.
Date objects are treated as the DATE 00:00:00 datetime in querysets. Sou you can filter the datetime between today and tomorrow:
import datetime
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
viewteam.daily_risk_set.filter(team=4713,
created__gte=today, created__lt=tomorrow) \
.order_by('-created')[:1]:

Django filter by datetime, after converting string to datetime

I'm trying to filter my query by a datetime. This datetime is the datetime for the value range the customer wants to know information for. I'm trying to set it to the first of the month selected by the customer. I pass the month number convert it to the correct string format and then convert to a datetime object because simply looking for the string object was returning no values and Django's documentation says you need to do it like:
pub_date__gte=datetime(2005, 1, 30)
Code:
if 'billing-report' in request.POST:
customer_id = int(post_data['selected_customer'])
This is the code I use to get the selected customer date and turn it into a tupple
if 'billing-report' in request.POST:
customer_id = int(post_data['selected_customer'])
selected_date = int(post_data['month'])
if selected_date < 10:
selected_date = '0'+str(selected_date)
year = datetime.now()
year = year.year
query_date = str(year) + '-' + str(selected_date) + '-01'
query_date_filter = datetime.strptime(query_date, "%Y-%m-%d")
compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = query_date_filter)
django debug shows: datetime.datetime(2014, 10, 1, 0, 0)
query_date looks like: 2014-07-01 before it is converted
.
No error but no data is returned
I used to use:
compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = datetime(query_date_filter))
which was causing the error. I'm sorry for changing my question as it evolved that is why I'm re-including what I was doing before so the comments make sense.
Almost all of that code is irrelevant to your question.
I don't understand why you are calling datetime on query_date. That is already a datetime, as you know because you converted it to one with strptime earlier. So there's no need for any more conversion:
ComputeUsages.objects.filter(customer_id=customer_id).filter(values_date=query_date)
Well after spending sometime exploring setting the query filter to datetime(year, month, day) I came to the realization that django doesn't convert it to a neutral datetime format it has to match exactly. Also my data in the database had the year, day, month.
Learning point:
You have to use the datetime() exactly how it is in the database django does not convert to a neutral format and compare. I assumed it was like writing a query and saying to_date or to_timestamp where the db will take your format and convert it to a neutral format to compare against the rest of the db.
Here is the correct way
compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = datetime(year, day, selected_month))

Categories

Resources