在用python的django框架进行web开发的时候,出现了一个错误:
Traceback (most recent call last): File "D:Python27libsite-packagesdjangocorehandlersexception.py", line 41, in inner response = get_response(request) File "D:Python27libsite-packagesdjangocorehandlersase.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "D:Python27libsite-packagesdjangocorehandlersase.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:pythonWorkworkSpaceismsspmspmservercoreviewproxysView.py", line 37, in proxys_list return JsonResponse(content) File "D:pythonWorkworkSpaceismsspmspmservercore esponse.py", line 32, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "D:Python27libjson\__init__.py", line 250, in dumps sort_keys=sort_keys, **kw).encode(obj) File "D:Python27libjsonencoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "D:Python27libjsonencoder.py", line 270, in iterencode return _iterencode(o, 0) File "D:pythonWorkworkSpaceismsspmspmservercoreencoder.py", line 25, in default return timezone.localtime(o).strftime(DATE_TIME_FORMAT) File "D:Python27libsite-packagesdjangoutils imezone.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中设置:
-
TIME_ZONE = 'Asia/Shanghai'
-
USE_TZ = True
分析原因:
启用 USE_TZ = True 后,处理时间方面,有两条 “黄金法则”:
保证存储到数据库中的是 UTC 时间;
在函数之间传递时间参数时,确保时间已经转换成 UTC 时间;