时间数据格式不匹配错误

时间:2016-05-11 19:35:21

标签: python python-3.x datetime python-datetime

我有一段代码,目前在我的本地python(anaconda python 3.5.1)上运行没有任何问题,但是当我在生产中运行它时给我一个奇怪的错误(我的印象是环境非常类似,python版本是相同的。)

以下是相关的代码段:

ds_date_format = "%Y%m%d"
rta_date_format = '%a %b %d %H:%M:%S %Z %Y'

d1 = datetime.datetime.strptime(date_ds, ds_date_format)
d2 = datetime.datetime.strptime(date_rta, rta_date_format).replace(hour=0, minute=0, second=0)

我得到的错误的追溯。

{
  "error": {
    "traceback": [
      "Traceback (most recent call last):\n",
      "  File \"/opt/conda/lib/python3.5/site-packages/tornado/web.py\", line 1445, in _execute\n    result = yield result\n",
      "  File \"/opt/conda/lib/python3.5/site-packages/tornado/gen.py\", line 1008, in run\n    value = future.result()\n",
      "  File \"/opt/conda/lib/python3.5/site-packages/tornado/concurrent.py\", line 232, in result\n    raise_exc_info(self._exc_info)\n",
      "  File \"<string>\", line 3, in raise_exc_info\n",
      "  File \"/opt/conda/lib/python3.5/site-packages/tornado/gen.py\", line 1017, in run\n    yielded = self.gen.send(value)\n",
      "  File \"<string>\", line 6, in _wrap_awaitable\n",
      "  File \"rtamatching.py\", line 171, in post\n    self.write(await self.rta_matcher.check_matches(data))\n",
      "  File \"rtamatching.py\", line 114, in check_matches\n    date_match_scores.append(date_similarity(date, user_feeds[key]['TransactionDate']))\n",
      "  File \"/opt/api/functions.py\", line 9, in date_similarity\n    d2 = datetime.datetime.strptime(date_rta, rta_date_format).replace(hour=0, minute=0, second=0)\n",
      "  File \"/opt/conda/lib/python3.5/_strptime.py\", line 500, in _strptime_datetime\n    tt, fraction = _strptime(data_string, format)\n",
      "  File \"/opt/conda/lib/python3.5/_strptime.py\", line 337, in _strptime\n    (data_string, format))\n",
      "ValueError: time data 'Wed Mar 09 21:59:50 PST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'\n"
    ],
    "code": 500,
    "message": "Internal Server Error"
  }
}

该值错误似乎很奇怪,因为据我所知,指定的格式是正确的。

1 个答案:

答案 0 :(得分:0)

正如M.T所指出的,strptime()和时区似乎存在问题。按如下方式重写我的代码实现了我期望的结果:

from dateutil.parser import parse    
...
d1 = parse(date_ds)
d2 = parse(date_rta)
...