How to remove/convert naive time to time zone aware in Django - python

I am trying to read a date of format DD-MM-YYYY format from HTML and Compare it with the datetime field named as widget_created_at in my model.
if data["field"] == "widget_created_at":
date = datetime.strptime(data["data"], "%d-%m-%Y").date()
if data["option"] == "before":
filter_query = Q(widget_created_at__lt=date)
Then whenever this query is used for filtering in the below code
blogs = blogs.filter(filter_query)
RunTime warning for naive datetime appears. I tried every solution i found from here and google but the Error is still there. Please tell me how to avoid it.
Thanks

The date you are creating for your filter has no timezone.
Have you looked at pytz to "localize" the filter date? This would allow you to add a timezone to the filter date?

Related

Query Django data base to find a column with a specific value and update that column value

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()

how to make query from datetime filed smaller than current datetime

in my django website i need to make query based on datetime filed that are smaller than now this is my query in views.py :
meetings=Meeting.objects.filter(date_time__lt=datetime.now()).filter(Q(members_email__icontains=str(request.user.email))|Q(host=request.user))
and this is datetime filed in models.py :
date_time = models.DateTimeField(null=True,blank=True)
but it returns nothing i don't know how to solve this problem
any suggestion?

Peewee and SQLite returning incorrect date format

I have built a web app in Python and Flask and am having trouble pulling the date and time from my SQLite database.
I enter the date into the DB with the following line-
order.order_placed = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Which with my current example enters the following into the DB -
2018-05-01 12:08:49
But when I call order.order_placed I get datetime.date(2018, 5, 1)
Even if I call str(order.order_placed) I get '2018-05-01'
Can someone help me get the full date and time out of the database? Thanks!
It's possible that you're using DateField when in actuality you want to use DateTimeField.
Furthermore, you don't need to call strftime before storing the data. Peewee works nicely with Python datetime objects.

Display a time using a given timezone in Django

I'm developing a Django app for logging dives and each dive has a datetime and a timezone in it. I'm using the django-timezone-field app for the timezone.
class Dive(models.Model):
...
date_time_in = models.DateTimeField(default=timezone.now)
timezone = TimeZoneField(default=timezone.get_current_timezone_name())
So the user is able to enter a datetime string ("2016-07-11 14:00") and select a timezone ("Asia/Bangkok" - UTC+0700), I then set the timezone of the datetime to the one given in my view like this:
def log_dive(request):
if request.method == 'POST':
form = DiveForm(request.POST)
if form.is_valid():
dive = form.save(commit=False)
date = dive.date_time_in
date = date.replace(tzinfo=None)
dive.date_time_in = dive.timezone.localize(date)
dive.save()
The database then stores the datetime as UTC in the database (SELECT statement gives it in my local timezone):
# SELECT date_time_in, timezone FROM divelog_dive ORDER BY number DESC;
date_time_in | timezone
------------------------+------------------
2014-07-11 17:00:00+10 | Asia/Bangkok
Now there are two things I'm struggling with:
1) I want to display the dates in the given timezone, however I can't seem to stop it defaulting to the TIME_ZONE setting.
2) If the user edits the record, the time displayed in the edit field should be the one they originally entered (14:00), instead it's showing it in the current timezone (17:00).
Check your timezone setting in settings.py
Do you have USE_TZ = true in your settings file? If you created your app using the djangoadmin-startproject command, it is set by default.
Also, I struggled with timezones at my last job but found that using pytz really helped. Have you tried that package yet?
EDIT: Ok man I may be way off, but since noone else has answered and I feel the timezone struggle, here is something I noticed...
You are replacing the date object with tz_info=None, but wouldn't you want to instead replace that with the timezone from the database? So you would get that timezone and do a replace using the valid format (tzinfo=blah...)?
Like I said I may be way off but if that helps there you go.
Sorry, I don't think I explained my problem very well. I finally figured this out, so I'll answer my own question.
1) turned out to be easy, Django have a template tag for displaying times in a given zone:
{{ dive.date_time_in|timezone:dive.timezone|date:"Y-m-d H:i e" }}
For 2), I came across [1] which lead me to this solution: In the view, after getting the object from the database, I use astimezone(...) to convert the date value (which the DB stores as UTC) into the given timezone. I then use replace(tzinfo=None) to make it naive and then it displays correctly on my form.
def edit_dive(request, dive_id=None):
dive = None
if dive_id != None:
dive = get_object_or_404(Dive, pk=dive_id)
local_date = dive.date_time_in.astimezone(timezone(str(dive.timezone)))
dive.date_time_in = local_date.replace(tzinfo=None)
[1] http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/

Compare date and datetime in Django

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))

Categories

Resources