How to solve strptime () caused naive datetime RuntimeWarning?

I am trying to code without throwing any warnings to my console. So far, I've been pretty good at avoiding it, for now this case, which seems like chicken and egg 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 throws this warning:

RuntimeWarning: DateTimeField got naive datetime (2013-01-19) 00:00:00) and timezone support is active.)

Its type is odd as I need to convert unicode to datetime first, before I can convert datetime object to datetime object (timezone enabled) in the fourth line.

Any suggestions from the experts?

thank

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]

      

+3


source to share


2 answers


From the comments on your question, I assume that what you actually have in your code is something like this:

from datetime import datetime as dt 

last_contacted = "19/01/2013"
current_tz = timezone.get_current_timezone()
model_instance.date_time = dt.strptime(last_contacted, get_current_date_input_format(request))
model_instance.date_time = current_tz.localize(date_time)

      

where model_instance

is an instance of the model that has a DateTimeField named date_time

.

class MyModel(models.Model)
    ....
    date_time = DateTimeField()

      



The Python function datetime.strptime

returns a naive object datetime

that you are trying to assign DateTimeField

, which then generates a warning because using non-naive datetime

objects is incorrect when timezone support is enabled.

If you combine calls on strptime

and localize

on the same line, then the full calculation of the conversion from naive datetime

to non-naive datetime

is done before the assignment, date_time

and so on, you will not get an error in this case.

Additional note: your function get_current_date_input_format

must return a specific default timezone to use if there is no timezone in the request, otherwise the call strptime

will fail.

+7


source


Have you enabled USE_TZ in the settings file?

USE_TZ = True

      



Also, from the documentation , you can take some more specific steps.

0


source







All Articles