Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve the strptime() caused naive datetime RuntimeWarning?

Tags:

python

django

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]
like image 986
Houman Avatar asked Oct 26 '25 10:10

Houman


1 Answers

From the comments to your question I am guessing that what you really 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 a Model which has a DateTimeField named date_time.

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

The Python datetime.strptime function returns a naive datetime object which you are attempting to assign to the DateTimeField which is then generating a warning because the use of non-naive datetime objects is incorrect when timezone support is enabled.

If you combine the calls to strptime and localize on a single line, then the complete calculation of converting from a naive datetime to non-naive datetime is done before assigning to date_time and so you won't get an error in this case.

Additional note: Your get_current_date_input_format function should return some default timezone to use in the event that there is no timezone in the request, otherwise the strptime call will fail.

like image 59
Austin Phillips Avatar answered Oct 28 '25 23:10

Austin Phillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!