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

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.

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

RuntimeWarning: DateTimeField received a naive datetime in django

I am trying to set a DateTimeField for one of my django models. My code looks like this:
dt = datetime.fromtimestamp(mktime(parsed_feed.updated_parsed))
feed.updated = dt
updated_parsed is struct in the format :
time.struct_time(tm_year=2016, tm_mon=4, tm_mday=26, tm_hour=8, tm_min=20, tm_sec=43, tm_wday=1, tm_yday=117, tm_isdst=0)
And updated is obviously the django DateTimeField. I am trying to convert the struct into a datetime object, and then set it to my field. Everything works nicely, and the correct date and time is set, however, I get this error (warning) in my console:
RuntimeWarning: DateTimeField Feed.updated received a naive datetime (2016-04-26 08:25:08) while time zone support is active.
RuntimeWarning)
How do I integrate timezone support into the datetime object (dt)?
As explained in this answer:
The following line creates a naive (non-timezone aware) datetime:
creationDate = datetime.datetime.now()
Try changing that line to:
creationDate = timezone.now()
Don't forget to import timezone at the beginning of your code:
from django.utils import timezone
Use the pytz package.
So import pytz into your views.
t = pytz.timezone('Europe/Warsaw').localize(
datetime(2013, 5, 11, hour=11, minute=0))
Your timezone should be set in your settings.py
datetime and timezone conversion with pytz - mind blowing behaviour

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

django timeuntil ignoring timezone

I am testing django 1.4 features. for me the most important is the TZ control.
I am using PG and the DateTimeField is working perfect saving the datetime having in count settings.TIME_ZONE also Im setting other differents timezones with pytz and looks good.
but the problem is with timesince tag, is ignoring the TZ:
from django.utils import timezone
from django.utils.timesince import timeuntil
class Foo(models.Model):
date = models.DateTimeField()
def remaining(self):
res = timeuntil(self.date, datetime.datetime.now(tz=timezone.get_current_timezone()))
return res
foo.remaining() is always returning the remaining count with the default timezone.
thanks in advance.

Categories