Python Pimping / Monkey Fix

I want to do a simple thing: monkey-patch datetime. I cannot do this for sure, since it datetimeis a class C.

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 a file called datetime.py inside the package that I called the pimp.

From the error message I was 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 cannot have a module called datetimeimporting anything from another module called datetime.

How do I continue my module and class with a name datetime?

+4
1

, , your_lib.datetime. datetime .

Python 2, :

from __future__ import absolute_import

. , :

your_lib/
├── datetime.py
└── __init__.py

:

$ python -c 'import your_lib.datetime'

datetime.py:

from __future__ import absolute_import
from datetime import timedelta
+2

All Articles