Django

Django,RuntimeWarning: DateTimeField received a naive datetime while time zone support is active.

189bigman 2023. 1. 9. 22:43

장고에서 시간 정보를 저장하다가 RuntimeWarning: DateTimeField User.created_at received a naive datetime (2021-12-23 05:53:31) while time zone support is active. 경고 메세지가 나왔다.

동작은 정상작동 했으나 경고가 나오는 이유를 알아보기 위해 찾아봤다.

 

일단 구글 번역을 번역을 해봤다.

Django,RuntimeWarning: DateTimeField는 표준 시간대 지원이 활성화된 동안 순진한 datetime을 받았습니다.

순진한 data time을 받았습니다. naive datetime 을 말하는거 같다.

 

그럼 naive datetime은 뭘까?

datetime 종류는 2가지

파이썬 공식문서의 내용이다.

Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.

Naive datetime

타임존정보가 포함되지 않은 datetime 객체  (Naive = 2020-03-22 09:46:11.056746)

Aware datetime

타임존정보가 설정된 datetime 객체 (Aware = 2020-03-22 09:46:11.056746+09:00)

 

원인

에러와 공식문서를 봤을때 에러의 원인은 Aware datetime객체로 저장해야 하는데 Naive datetime 객체로 저장하려고 해서

생긴 오류이다.

 

해결방법

1. django의 settings.py에서 UTC설정을 끈다.

settings.py 에서 USE_TZ = False 로 변경 하면 에러가 뜨지 않는다.

이렇게하면 오류는 나지 않지만 근본적 해결은 아니다.

 

2.Aware datetime객체로 저장한다.(추천)

 

#1111 2023-01-09 13:38:17.929766+00:00
#222 2023-01-09 13:38:17.929777+00:00

 

이렇게 Aware datetime 객체를 생성 저장으로 오류가 생기지 않도록 할 수 있다.