我试图用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")
视图是这样使用的:
^{pr2}$当我在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环境的某些东西似乎破坏了一切,我似乎找不到它是什么。我错过了什么明显的东西吗?如有任何建议,我们将不胜感激。在
我想您在Python中点击了this bug:
更进一步,有人指出:
(这可能就是它在REPL中对您有效的原因。)
MDT
时区名称是导致它失败的原因。你可以把它剥离出来确认一下。尝试在Django shell中运行此命令,它将起作用:可能的解决方案:在尝试解析时间字符串之前,去掉它的最后一部分;或者使用dateutil,它工作正常:
^{pr2}$相关问题 更多 >
编程相关推荐