RuntimeWarning: DateTimeField received a naive datetime in django - python

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

Related

How do I force Django queryset return datetime field in current timezone?

I have Django model:
class Deal(models.Model):
...
created_at = models.DateTimeField(auto_now_add=True)
When I get created_at value by queryset, it always return to me the datetime value with tzinfo=<UTC> like this:
Deal.objects.filter(id=62).values('created_at')
<QuerySet [{'created_at': datetime.datetime(2015, 10, 26, 4, 10, 54, 997000, tzinfo=<UTC>)}]>
How do I force queryset return datetime value in current timezone (e.g Asia/Ho_Chi_Minh)?
Django always saves datetimes in UTC, and they are usually returned in UTC as well (depending on the database and database adapter settings). You normally select a timezone by using activate(). That affects various things, like the way datetimes are displayed in templates.
If you want to explicitly convert the timezone for some reason, you can easily do that with localtime(). For example:
from django.utils.timezone import localtime
import pytz
tz = pytz.timezone("Asia/Ho_Chi_Minh")
deals_utc = Deal.objects.filter(id=62).values("created_at")
deals_local = {"created_at": localtime(dt, tz) for dt in deals_utc.values()}
In your settings.py file, change TIME_ZONE value.
TIME_ZONE='Asia/Ho_Chi_Minh'

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.

How to correct wrong timezone offset in pytz and django?

I am writing a project with django.
I am using timezone 'Asia/ShangHai', when I am getting the datetime object, the offset of the timezone is incorrect and was:
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
And the offset should be +8:00:00
AFAICR, the problem was not there before.
How can I solve this problem?
You can use this function with django:
def add_local_tz_to_native_time(native_dt):
# type: (datetime.datetime) -> datetime.datetime
from django.utils import timezone
if timezone.pytz is None:
return native_dt.replace(tzinfo=timezone.get_current_timezone())
else:
return timezone.get_current_timezone().localize(native_dt)

DateTimeField received a naive datetime

I have model with DateTimeField column.
I'm try to insert row with database current_time value directly into table by sql query.
My sql query for MySQL database like:
INSERT INTO MyTable (..., my_datetime, ...) VALUES (..., current_time, ...)
And get:
RuntimeWarning: DateTimeField ModelName.field_name received a naive
datetime (2014-01-09 22:16:23) while time zone support is active.
How to insert current time directly into table by sql query without warning?
Further to falsetru's answer, if the datetime has already been created you can convert it to timezone aware:
from django.utils import timezone
my_datetime = timezone.make_aware(my_datetime, timezone.get_current_timezone())
Use django.utils.timezone.now instead of datetime.datetime.now.
from django.utils import timezone
current_time = timezone.now()
You can also make the datetime time zone aware with localize from pytz, as explained here.
UTC:
import pytz
dt_aware = pytz.utc.localize(dt_naive)
Any other time zone:
import pytz
tz = 'Europe/Berlin' #or whaterver timezone you want
dt_aware = pytz.timezone(tz).localize(dt_naive)
And here the list of timezones.

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