我正在尝试在 Django 中编写一个页面,该页面使用 JavaScript 获取特定任务的开始和完成时间,并使用 AJAX 发布它。由于 JavaScript 似乎没有很好的格式化日期的方法,我只发送一个日期字符串,如 Fri May 13 2016 22:00:56 GMT-0600 (MDT)
是被 Python 解析为字符串。
这是我解析字符串的函数:
def get_js_date(string):
date = datetime.datetime.strptime(string, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
return date.strftime("%Y-%m-%d %H:%M:%S %Z")
然后 View 像这样使用它:
def review_new(request):
if request.method == 'POST':
review = Review(
user = request.user,
start = get_js_date(request.POST.get('start')),
finish = get_js_date(request.POST.get('finish'))
)
review.save()
当我在 Python REPL 中导入该函数时,它工作正常:
>>> from checks.utilities import get_js_date
>>> get_js_date('Fri May 13 2016 22:00:56 GMT-0600 (MDT)')
'2016-05-13 22:00:56 MDT'
但是当我通过 ./manage.py shell
运行它时,它中断了:
>>> from checks.utilities import get_js_date
>>> get_js_date('Fri May 13 2016 22:00:56 GMT-0600 (MDT)')
Traceback (most recent call last):
File "/home/phin/virtualenvs/testenv/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "/home/phin/virtualenvs/testenv/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/phin/grappleshark/checks/utilities.py", line 4, in get_js_date
date = datetime.datetime.strptime(string, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
File "/usr/lib64/python3.5/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.5/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data 'Fri May 13 2016 22:00:56 GMT-0600 (MDT)' does not match format '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
关于 Django 环境的某些东西似乎正在破坏一切,我似乎无法找到它是什么。我错过了一些明显的东西吗?如有任何建议,我们将不胜感激。
最佳答案
我认为您正在点击 this bug在 Python 中:
The documentation for %Z says it matches
EST
among others, but in practice it doesn't.
在帖子的更下方有人指出:
Looking at the code, the only timezone strings it recognizes are utc, gmt, and whatever is in time.tzname (EST and EDT, in my case).
(这可能就是它在 REPL 中适合你的原因。)
MDT
时区名称是导致它失败的原因。您可以通过剥离来确认这一点。尝试在 Django shell 中运行它,它会起作用:
datetime.datetime.strptime('Fri May 13 2016 22:00:56 GMT-0600',
'%a %b %d %Y %H:%M:%S GMT%z')
可能的解决方案:在尝试解析之前删除时间字符串的最后部分;或使用 dateutil效果很好:
from dateutil import parser
parser.parse('Fri May 13 2016 22:00:56 GMT-0600 (MDT)')
关于javascript - 为什么 datetime.strptime 在使用 Django 运行时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222403/