Luí*_*rme 5 python datetime python-import
我想做一件简单的事情:monkey-patch datetime。我不能完全那样做,因为datetime是 C 类。
所以我写了下面的代码:
from datetime import datetime as _datetime
class datetime(_datetime):
def withTimeAtMidnight(self):
return self.replace(hour=0, minute=0, second=0, microsecond=0)
这是在我称为 pimp 的包中名为 datetime.py 的文件中。
从我得到的错误消息中:
回溯(最近一次调用最后一次):
文件“run.py”,第 1 行,在
从 pimp.datetime 导入日期时间
文件“/home/lg/src/project/library/pimp/datetime/datetime.py”,第 1 行,在
从日期时间导入日期时间为 _datetime
导入错误:无法导入名称日期时间
我假设我不能有一个名为datetime从另一个名为datetime.
我应该如何继续保持我的模块和类的命名datetime?
将模块放入包中,例如your_lib.datetime. 您不应该使用datetime顶级模块的名称。
如果您使用的是 Python 2,请在顶部添加:
\n\nfrom __future__ import absolute_import\nRun Code Online (Sandbox Code Playgroud)\n\n禁止包内隐式相对导入。那么如果你的目录结构是:
\n\nyour_lib/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 datetime.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 __init__.py\nRun Code Online (Sandbox Code Playgroud)\n\n以下命令有效:
\n\n$ python -c 'import your_lib.datetime'\nRun Code Online (Sandbox Code Playgroud)\n\n哪里datetime.py:
from __future__ import absolute_import\nfrom datetime import timedelta\nRun Code Online (Sandbox Code Playgroud)\n