Reputation: 103
I am trying to insert some records to a Django Model which include some old dates in unix ctime Format. I am comverting it to YYYY-MM-DD hh:mm:ss and saving it to a model in datetime field.
While running a import job ( Function which is converting the unix dates to YYYY-MM-DD hh:mm:ss) and saving it , I am getting a warning below
C:\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py:1421: RuntimeWarning: DateTimeField SensorRecords.aqdate received a naive datetime (2012-07-06 05:00:00) while time zone support is active.
RuntimeWarning)
How should I import it so to avoid this ?
This is my Converter Function
def ctodatetime (ctimeinput):
etime=time.ctime(int(ctimeinput))
btime=datetime.datetime.strptime(etime,"%a %b %d %H:%M:%S %Y")
print(btime)
return btime
Here is a snippet of my model
class SensorRecords(models.Model):
sensorid = models.IntegerField(default=0)
aqdate = models.DateTimeField(default= "1970-01-01 00:00:00")
cmpflaf = models.BooleanField(default=0)
Upvotes: 3
Views: 3461
Reputation: 557
A Django-specific solution could be using django.utils.timezone
, in the following manner:
from datetime import datetime
from django.utils import timezone
from django.conf import settings
def ctodatetime(ctimeinput):
etime = time.ctime(int(ctimeinput))
btime = datetime.strptime(etime, "%a %b %d %H:%M:%S %Y")
tz = getattr(settings, 'TIME_ZONE', None)
return timezone.make_aware(btime, tz)
This relies on the fact that btime
will be a naive timestamp, and makes use of Django’s make_aware() to convert it to a timezone-aware timestamp.
Upvotes: 1
Reputation: 88499
You should add tz_info
to the datetime
object before passing to the model instance.
import pytz
import datetime
import time
from django.conf import settings
def ctodatetime(ctimeinput):
etime = time.ctime(int(ctimeinput))
btime = datetime.datetime.strptime(etime, "%a %b %d %H:%M:%S %Y")
tz_aware_datetetime = btime.replace(tzinfo=pytz.timezone(settings.TIME_ZONE))
print(tz_aware_datetetime)
return tz_aware_datetetime
The .replace()
function returns a new datetime object
For more info, refer this SO post RuntimeWarning: DateTimeField received a naive datetime
Upvotes: 4