ValueError: localtime() cannot be applied to a naive datetime问题

 

在用python的django框架进行web开发的时候,出现了一个错误:

 

Traceback (most recent call last):
  File "D:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\pythonWork\workSpace\isms\spm\spm\server\core\view\proxysView.py", line 37, in proxys_list
    return JsonResponse(content)
  File "D:\pythonWork\workSpace\isms\spm\spm\server\core\response.py", line 32, in __init__
    data = json.dumps(data, cls=encoder, **json_dumps_params)
  File "D:\Python27\lib\json\__init__.py", line 250, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "D:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "D:\pythonWork\workSpace\isms\spm\spm\server\core\encoder.py", line 25, in default
    return timezone.localtime(o).strftime(DATE_TIME_FORMAT)
  File "D:\Python27\lib\site-packages\django\utils\timezone.py", line 216, in localtime
    raise ValueError("localtime() cannot be applied to a naive datetime")
ValueError: localtime() cannot be applied to a naive datetime

 

 

在这里找到了解决方案:https://github.com/django-tastypie/django-tastypie/pull/561

django中的时区设置TIME_ZONE,USE_TZ

在settings.py中设置:

 

  1.  
    TIME_ZONE = 'Asia/Shanghai'
  2.  
    USE_TZ = True

 

分析原因:

 启用 USE_TZ = True 后,处理时间方面,有两条 “黄金法则”:
保证存储到数据库中的是 UTC 时间;
在函数之间传递时间参数时,确保时间已经转换成 UTC 时间;

posted @ 2020-08-11 02:22  sewen  Views(1303)  Comments(0Edit  收藏  举报