Kevin Bedell
Kevin Bedell

Reputation: 13404

PYTHON: RuntimeWarning: DateTimeField received a naive datetime while time zone support is active. RuntimeWarning)

I'm working with an API that passes me a time/date field that they cannot guarantee will always have timezone info in it.

From their docs, this field could be either:

Empty String,
YYYY-MM-DD,
YYYY-MM-DDTHH:MM:SS, or
YYYY-MM-DDTHH:MM:SS+TIMEZONE

When I try to save that field to my model in the database it generates this error in the case where the data comes without timezone information. The field I'm saving this value into is defined in its model as:

my_timedate_field = models.DateTimeField()

At a minimum I'd like to suppress the warnings from being generated with each record saved. Is there anything specific I can do to make this a bit cleaner?

Edit: The warnings are:

RuntimeWarning: DateTimeField my_timedate_field received a naive datetime while time zone support is active. RuntimeWarning)

These warnings show up in my logs every time I process an api call -- sometimes 5-10 times per api call given how the elements show up.

Upvotes: 0

Views: 11630

Answers (1)

Kevin Bedell
Kevin Bedell

Reputation: 13404

I figured this out.

It turns out that -- assuming I can't count on timezone info always being a part of the string passed from the incoming API -- this is the best I can do.

By using the django model declaration:

api_time = models.DateTimeField()

time values sent in that do not contain timezone info can still be stored in that field. The warning occurs to let you know that you are saving a non-timezone field in a timezone-aware database field.

Again -- here's the warning:

RuntimeWarning: DateTimeField api_time received a naive datetime 
  (2018-08-03 09:04:25) while time zone support is active.

Upvotes: 3

Related Questions