Django datetime comparison - python

I am trying to find records in a Django app where a datetime field is older than the current datetime.
I have something like this:
records = Record.objects.filter(my_field__lte=datetime.now())
However, it only finds records where the date is older than today (if there are records older than now but on today's date, they are not returned.)
Edit: Just to clarify. If the field is set to 19:59:00 12-10-2011 and the current time is 20:00:00 12-10-2011, then I would want this record to be returned in the queryset. However, it's not actually being returned until the query is run on the following day. (It's run every five minutes on a cronscript and is used to send emails based on this datetime field)
Hope that clears it up.
BTW, I am using MySQL
Can anyone help?
Any advice appreciated.
Thanks

check in database if you can see time attributes, next check if you have models.DateTimeField in your models and no models.DateField by error

Just test for midnight tomorrow instead of now:
now = datetime.now()
midnight = datetime(now.year, now.month, now.day+1, 0, 0, 0)
records = Record.objects.filter(my_field__lt=midnight)
Or you can use date.today and timedelta to get the same effect:
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
records = Record.objects.filter(my_field__lt=tomorrow)

Related

failed to delete the start_date with django queryset

I am trying to delete the data between start_date and_date using django.
Here is the code I am using:
Porfolio.objects.filter(portfolio_id=portfolio_id, date__gte=start_date, date__lte=end_date).delete()
Problem:
whatever the start and end_date I am using, the start_date is not deleted while all the period afterward is deleted until end_date. and I am sure that in all cases I tested I have data in the start_date to delete. \
date is defined as date = models.DateField(). I use the format 'year-month-day' as a string in input (expl: start_date='2022-01-01'). No hours, minutes or timezones.\
Could not figure out why I am getting this behaviour.
You should use range lookup and Q() objects together as stated by #AbdulAzizBarkat in the above comment so:
from django.db.models import Q
Porfolio.objects.filter(Q(portfolio_id=portfolio_id) & Q(date__range=(start_date,end_date))).delete()
It will only work correctly if date is DateField not DateTimeField according to docs.

Using Tweepy, is there a way to be able to interact with the UTC time that 'created_at' returns?

In my case, I want to be able to get what's returned by 'created_at' and use it in an if statement or loop or anything else.
mentions = api.mentions_timeline(tweet_mode="extended")
for tweet in reversed(mentions):
created_at_id = tweet.id
created_at = tweet.created_at
print(f"tweet was made at {created_at}")
tweet was made at 2021-05-14 00:22:23 # This is what is printed
This is fine and dandy, the time is returned in UTC format but what if I wanted to compare the time and date (just time if possible) and use it in a statement?
if *hour of the tweet* 12 hours before datetime.datetime.now():
print("yes")
# Some pseudocode here because I still have to figure out how to be able to compare the current date
So the question stands, how could I access the time of the tweet so I can use it in a statement? Any help would be greatly appreciated!
Let me know if this is what you're looking for. If not, I will correct it.
from dateutil.parser import parse
from datetime import datetime, timedelta
twelve_hours_before = (datetime.now() - timedelta(hours=12)).strftime('%Y-%m-%d %H:%M:%S')
time_string = '2021-05-14 23:35:23'
# use your datetime object for parse(time_string).
if parse(twelve_hours_before) <= parse(time_string):
print('yes')

questions about using pymongo to insert date and time into mongo

I want to insert date and time into mongo ,using pymongo.
However, I can insert datetime but not just date or time .
here is the example code :
now = datetime.datetime.now()
log_date = now.date()
log_time = now.time()
self.logs['test'].insert({'log_date_time': now, 'log_date':log_date, 'log_time':log_time})
it show errors :
bson.errors.InvalidDocument: Cannot encode object: datetime.time(9, 12, 39, 535769)
in fact , i don't know how to insert just date or time in mongo shell too.
i know insert datetime is new Date(), but I just want the date or time filed.
You are experiencing the defined behavior. MongoDB has a single datetime type (datetime). There are no separate, discrete types of just date or just time.
Workarounds: Plenty, but food for thought:
Storing just date is straightforward: assume Z time, use a time component of 00:00:00, and ignore the time offset upon retrieval.
Storing just time is trickier but doable: establish a base date like the epoch and only vary the time component, and ignore the date component upon retrieval.

SQL Where Clause and Django Timezone

I have noticed that when I return records from my SQL database using the following: the_records = records.objects.filter(datetime__contains="2015-01-15"), I get back the wrong records because the timezone is affecting the function call somehow - I know this because if I temporarily disable the timezone, the right records are returned. Can anyone offer assistance on what I should do to fix this problem (I still need to use the timezone).
Regards, Mark
I'm assuming that datetime is a Django DateTime field, and you're trying to get the results that have a value that matches the date '2015-01-15', ignoring the actual time.
In that case, you probably want to do a date query, like: Records.objects.filter(datetime__date=datetime.date(2015, 1, 15))
If you need to query your db with a timezone specific date, you can just create a datetime object that is aware of it's timezone.
Example:
# Get your timezone
from django.utils import timezone
my_timezone = timezone.get_current_timezone()
# Get create your timezone aware datetime object
from datetime import datetime
query_date = datetime(2015,01,15).replace(tzinfo=my_timezone)
# now you can run your query with a timezone specific datetime object
the_records = records.objects.filter(datetime=query_date)
This should solve your issue and get you the accurate results you need.
Please let me know if you still have any questions.
This link has more info related to django timezones if you are interested in learning more.

Django + Postgres Timezones

I'm trying to figure out what's going on with a timezone conversion that's happening in Django.
My view code is as below, it filters on a date range and groups on the day of creation:
def stats_ad(request):
start_date = datetime.datetime.strptime(request.GET.get('start'), '%d/%m/%Y %H:%M:%S')
end_date = datetime.datetime.strptime(request.GET.get('end'), '%d/%m/%Y %H:%M:%S')
fads = Ad.objects.filter(created__range=[start_date, end_date]).extra(select={'created_date': 'created::date'}).values('created_date').annotate(total=Count('id')).order_by("created_date")
The SQL query that is produced by django when I set the get variable of start to "01/05/2013 00:00:00" and the request end variable to "11/05/2013 23:59:00":
SELECT (created::date) AS "created_date", COUNT("ads_ad"."id") AS "total" FROM "ads_ad" WHERE "ads_ad"."created" BETWEEN E'2013-05-01 00:00:00+10:00' and E'2013-05-11 23:59:59+10:00' GROUP BY created::date, (created::date) ORDER BY "created_date" ASC
If I manually run that on my Postgresql database, it's all good, finds the following:
created_date total
2013-05-10 22
2013-05-11 1
However If I do the following:
for a in fads:
recent_ads.append({"dates": a['created_date'].strftime('%d/%m/%Y'), 'ads': a['total']})
It gives me the following output:
[{"dates": "09/05/2013", "ads": 1}, {"dates": "10/05/2013", "ads": 22}]
I'm at a loss at why it's changed the dates?
Anyone got any ideas?
Cheers,
Ben
Just a through on this. As of Django 1.4, Django now supports timezone aware dates and times. Perhaps it's possible that a conversion between your local timezone and the timezone that the data is stored in (possibly GMT) is taking place at some point. Perhaps that difference crosses the international date line, in which case the dates may show up differently.
Django has an interesting section describing the new timezone support feature.
https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/
That's what came to mind, anyway, when you described your problem. Hope this helps.
Python datetime from the standard python library is a mess.
Probably you are creating naive datetime instances (instances that lack timezone information).
# naive
now = datetime.datetime.now()
# TZ aware
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
In recent Django, datetime storage is always offset-aware, so you better convert naive datetimes - otherwise an automatic (and sometimes wrong) conversion will take place.
Take a look at the docs about Django Time Zones.

Categories