为什么datetime。在使用Django运行时抛出错误?

时间:2022-07-17 16:39:46

I'm trying to write a page in Django which gets start and finish times for a certain task using JavaScript and POSTs it using AJAX. Since JavaScript doesn't seem to have a very good way of formatting dates, I'm sending just sending a date string like Fri May 13 2016 22:00:56 GMT-0600 (MDT) to be parsed as a string by Python.

我正在尝试用Django编写一个页面,该页面使用JavaScript启动并完成某个任务,并使用AJAX发布它。由于JavaScript似乎没有很好的格式化日期,所以我只发送一个日期字符串,比如2016年5月13日星期五22:00:56 GMT-0600 (MDT),它被Python作为字符串解析。

Here is my function for parsing the string:

这是我解析字符串的函数:

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")

And the view uses it like so:

视图是这样使用的:

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()

When I import the function in the Python REPL, it works just fine:

当我在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'

But when I run it through ./manage.py shell, it breaks:

但当我试过的时候。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)'

Something about the Django environment seems to be breaking everything, and I can't seem to find what it is. Am I missing something obvious? Any suggestions would be appreciated.

《被解救的姜戈》的环境似乎打破了一切,我似乎找不到它是什么。我漏掉了什么明显的东西吗?如有任何建议,我们将不胜感激。

1 个解决方案

#1


1  

I think you are hitting this bug in Python:

我认为你是在用Python编写这个bug:

The documentation for %Z says it matches EST among others, but in practice it doesn't.

%Z的文档说它与其他文档中的EST相匹配,但实际上它并不匹配。

Further down in the thread someone points out that:

再往下,有人指出:

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).

查看代码,它识别的唯一时区字符串是utc、gmt和任何及时的字符串。tzname(在我的例子中是EST和EDT)。

(which might be why it works for you in REPL.)

(这可能就是为什么它对你起作用的原因。)

The MDT timezone name is what it causing it to fail. You can confirm this by stripping it out. Try running this in Django shell and it will work:

MDT时区名称是导致它失败的原因。你可以通过剥离它来确认这一点。试着在Django shell中运行它,它将会工作:

datetime.datetime.strptime('Fri May 13 2016 22:00:56 GMT-0600', 
                           '%a %b %d %Y %H:%M:%S GMT%z')

Possible solutions: strip out the last part of the time string before attempting to parse it; or use dateutil which works well:

可能的解决方案:在尝试解析时间字符串之前,将时间字符串的最后一部分去掉;或者使用dateutil,它工作得很好:

from dateutil import parser
parser.parse('Fri May 13 2016 22:00:56 GMT-0600 (MDT)')

#1


1  

I think you are hitting this bug in Python:

我认为你是在用Python编写这个bug:

The documentation for %Z says it matches EST among others, but in practice it doesn't.

%Z的文档说它与其他文档中的EST相匹配,但实际上它并不匹配。

Further down in the thread someone points out that:

再往下,有人指出:

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).

查看代码,它识别的唯一时区字符串是utc、gmt和任何及时的字符串。tzname(在我的例子中是EST和EDT)。

(which might be why it works for you in REPL.)

(这可能就是为什么它对你起作用的原因。)

The MDT timezone name is what it causing it to fail. You can confirm this by stripping it out. Try running this in Django shell and it will work:

MDT时区名称是导致它失败的原因。你可以通过剥离它来确认这一点。试着在Django shell中运行它,它将会工作:

datetime.datetime.strptime('Fri May 13 2016 22:00:56 GMT-0600', 
                           '%a %b %d %Y %H:%M:%S GMT%z')

Possible solutions: strip out the last part of the time string before attempting to parse it; or use dateutil which works well:

可能的解决方案:在尝试解析时间字符串之前,将时间字符串的最后一部分去掉;或者使用dateutil,它工作得很好:

from dateutil import parser
parser.parse('Fri May 13 2016 22:00:56 GMT-0600 (MDT)')