Django DateTime field received a naive datetime - python

I've seen this question asked a few times and I have followed the answers suggested, however im still getting the error:
/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: DateTimeField CircuitMaintenance.end_time received a naive datetime (2017-02-24 23:59:59) while time zone support is active.
RuntimeWarning)
From what ive read using django utils timezone instead of datetime.now() should of solved the issue, but it has not. I have also got the following settings in my settings.py
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
code
from django.utils import timezone
dt_now = timezone.now()
days_away = datetime(dt_now.year, dt_now.month, dt_now.day) + timedelta(days)
days_away_end = days_away + timedelta(hours=23,minutes=59,seconds=59)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=days_away, end_time__lte=days_away_end,circuit__site_data__site_type="Major Site")

Probably because the timezone info is lost when creating days_away. You can simply add timezone.now() to a timedelta:
days_away = timezone.now() + timedelta(days)
To default time data to midnight, you can use replace:
days_away = timezone.now().replace(hour=0,minute=0, second=0) + timedelta(days)
Also, note that what you have is a warning, not an error.

Related

How to convert Django model DateTimeField into local timezone and use Q object to filter

How to convert db DateTime field into local time and construct Q object for retrieving the dataset?
settings.py
LANGUAGE_CODE = 'en-us'
USER_TIME_ZONE = 'US/Pacific'
TIME_ZONE = 'UTC'
USE_TZ = True
models.py
class Hello(models.Model):
lucky_day = models.DateTimeField()
One record in db (UTC format)
2019-02-03 03:02:45
filter.py
# Client browser is Pacific time without time, date only.
localtime_str = '2019-3-2'
qset_filter = Q(lucky_day<to Pacific time from UTC>=localtime_str)
If you really want to first convert a utc datetime field to local datetime and then you want to filter based on localdatetime, you can use django aggregation to do that in this way:
YourModel.objects.annotate(new_local_datetime_field=convert_to_local_datetime('lucky_day')).filter(Q(new_local_datetime_field=some_other_datetime))
Reference to convert utc datetime to local datetime:
Convert UTC datetime string to local datetime
reference to django annotation: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.annotate

Set UTC when fixing naive datetimes with django.utils.timezone?

I'm using Django 1.9. I have a model with a DateTimeField:
class myModel(models.Model):
created = models.DateTimeField(blank=True, null=True)
And I have some naive text datetimes that look like this:
str = "2017-05-18T16:38:23"
If I do this:
d = datetime.strptime(result['last_modified'],
"%Y-%m-%dT%H:%M:%S")
mymodel.last_modified = dt_aware
I get a warning:
RuntimeWarning
439
/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1430:
RuntimeWarning: DateTimeField CV.last_modified received a
naive datetime (2015-04-07 09:09:20) while time zone support
is active.
So I'm trying this instead, but I'm aware that instead of current timezone I should really be using UTC, because I know the datestrings are UTC:
d = datetime.strptime(str, "%Y-%m-%dT%H:%M:%S")
dt_aware = tz.make_aware(d, tz.get_current_timezone())
mymodel.last_modified = dt_aware
How can I amend this to use UTC rather than current timezone? I don't want to disable timezone support in my app.

suppress django naive datetime warnings

I am concerned with a script that involves datetime module. I have to suppress 'object received a naive datetime while timezone is active' as there are other print statements in the script. My code is as below
script:
from datetime import datetime
date = datetime.now()
objName = className.objects.create(param=value, param=value, param=value, time=date, attachment=attachment)
models.py
class className(models.MOdel):
t = models.DateTimeField(null=True, blank=True)
How can I suppress naive datetime warnings?
Just disable the usage of timezones, as stated in the documentation:
USE_TZ = False

django time zone aware setup return local datetime in query

I have a django 1.5 setup with
TIME_ZONE = 'Asia/Jerusalem'
USE_TZ = True
in my settings file. I always set my datetime fields with tz aware datetime.
however when querying an object with models.DateTimeField
root.alert_set.all()
I get a local datetime instead of a tz aware one.
any ideas?
Thanks,
Shy

Django DateTimeField to compare with datetime.now()

I have a DateTimeField:
class Assignment (models.Model):
official_deadline = models.DateTimeField(null=True, blank=True)
I need to compare it to current date time, I have tried :
def official_deadline_past(self):
if datetime.datetime.today() > self.official_deadline:
return True
return False
But it returns always False I have also tried:
def official_deadline_past(self):
if datetime.datetime.now() > self.official_deadline:
return True
return False
But I have the same problem.
I have an information in the field: 2011-07-02 00:00:00 for example in the form generated by ModelForm
I had a similar issue comparing DateTimeField with datetime under python 2.7.3 and django 1.3.1
I don't think DateTimeField had good timezone support then or I didnt have it configured properly.
Whenever I specified a timezone for datetime field all my comparisons of DateTimeField > datetime would fail.
datetime was using local central time while DateTimeField was entered as eastern.
I ended up just putting a stupid hack in to add a timedelta(hours=1) to the datetime central object to "convert" it to eastern.
I have same issue , django model Datetime Field like only contain date(without time)
now = datetime.datetime.now()
q1=Q()
q1.children.append(Q(datetimefieldFrom__lte=now))
q1.children.append(Q(datetimefieldTo__gte=now))
ex.
now : "2020-12-11 17:17:58.000000"
datetimeFrom : "2020-12-11 16:17:58.000000"
datetimeFrom : "2020-12-11 18:17:58.000000"
it just pass "2020-12-11 00:00:00.000000" to compare
#johnjamesmiller, your timezone issue can be solve by modify the setting.py
TIME_ZONE = 'Asia/Hong_Kong'
USE_TZ = True

Categories