只有在 map 函数中导入 datetime 时,才能在 map 函数中使用 datetime。所以你的例子看起来像 -
def map(doc):
text = doc['text']
ti = doc['timestamp_ms']
ti = ti[:10] + '.' + ti[10:]
from datetime import datetime
dateArray = datetime.utcfromtimestamp(float(time))
if (dateArray.time().hour
However, you cannot load third-party libraries in the map function. I tried importing the nose test library and saw this in couch logs -
[[{initial_call,
{couch_os_process,init,['Argument__1']}},
{pid,<0.14643.4>},
{registered_name,[]},
{error_info,
{exit,
{function_clause,
[{couch_os_process,handle_info,
[{#Port<0.13927>,
{data,
{eol,
<<"{\"log\": \"Traceback (most recent call last):\n File \\"/usr/local/lib/python2.7/dist-packages/couchdb/view.py\\", line 79, in map_doc\n results.append([[key, value] for key, value in function(doc)])\n File \\"\\", line 5, in map\nImportError: No module named nose\n\"}">>}}},
{os_proc,"couchpy",#Port<0.13927>,
#Fun,
#Fun,5000}]},
{gen_server,handle_msg,5},
{proc_lib,init_p_do_apply,3}]},
[{gen_server,terminate,6},
{proc_lib,init_p_do_apply,3}]}},
如果您将第三方库直接安装在主机 python 安装上,而不是在您的虚拟环境中,您也许可以。但是,我不推荐这种做法。始终使用虚拟环境。