I want to do a simple thing: monkey-patch datetime
. I can't do that exactly, since datetime
is a C class.
So I wrote the following code:
from datetime import datetime as _datetime
class datetime(_datetime):
def withTimeAtMidnight(self):
return self.replace(hour=0, minute=0, second=0, microsecond=0)
This is on a file called datetime.py inside a package I called pimp.
From the error message I'm given:
Traceback (most recent call last): File "run.py", line 1, in from pimp.datetime import datetime File "/home/lg/src/project/library/pimp/datetime/datetime.py", line 1, in from datetime import datetime as _datetime ImportError: cannot import name datetime
I assume that I can't have a module called datetime
importing anything from another module called datetime
.
How should I proceed to keep my module and class named datetime
?
Put you module into a package e.g., your_lib.datetime
. You should not use datetime
name for a top-level module.
If you are on Python 2 then add at the top:
from __future__ import absolute_import
to forbid implicit relative imports inside a package. Then if your directory structure is:
your_lib/
├── datetime.py
└── __init__.py
The following command works:
$ python -c 'import your_lib.datetime'
where datetime.py
is:
from __future__ import absolute_import
from datetime import timedelta
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With