I am trying to code without throwing any warnings in my console. So far I have been pretty good at avoiding it until this one case, which seems like a chicken and egg situation to me.
from datetime import datetime as dt
last_contacted = "19/01/2013"
current_tz = timezone.get_current_timezone()
date_time = dt.strptime(last_contacted, get_current_date_input_format(request))
date_time = current_tz.localize(date_time)
The third line is throwing this warning:
RuntimeWarning: DateTimeField received a naive datetime (2013-01-19
00:00:00) while time zone support is active.)
Its kind of odd, since I need to convert the unicode into a datetime first before I can convert the datetime object into an datetime-aware object (with timezone support) in the forth line.
Any suggestions from experts?
Thanks
UPDATE:
def get_current_date_input_format(request):
if request.LANGUAGE_CODE == 'en-gb':
return formats_en_GB.DATE_INPUT_FORMATS[0]
elif request.LANGUAGE_CODE == 'en':
return formats_en.DATE_INPUT_FORMATS[0]
From the comments to your question I am guessing that what you really have in your code is something like this:
where
model_instanceis an instance of a Model which has a DateTimeField nameddate_time.The Python
datetime.strptimefunction returns a naivedatetimeobject which you are attempting to assign to theDateTimeFieldwhich is then generating a warning because the use of non-naivedatetimeobjects is incorrect when timezone support is enabled.If you combine the calls to
strptimeandlocalizeon a single line, then the complete calculation of converting from a naivedatetimeto non-naivedatetimeis done before assigning todate_timeand so you won’t get an error in this case.Additional note: Your
get_current_date_input_formatfunction should return some default timezone to use in the event that there is no timezone in the request, otherwise thestrptimecall will fail.