datetime - Python pimping / monkey-patching -


i want simple thing: monkey-patch datetime. can't exactly, since datetime c class.

so wrote following code:

 datetime import datetime _datetime

class datetime(_datetime): def withtimeatmidnight(self): return self.replace(hour=0, minute=0, second=0, microsecond=0)

this on file called datetime.py inside package called pimp.

from error message i'm given:

 traceback (most recent call last):   file "run.py", line 1, in      pimp.datetime import datetime   file "/home/lg/src/project/library/pimp/datetime/datetime.py", line 1, in      datetime import datetime _datetime importerror: cannot import name datetime 

i assume can't have module called datetime importing module called datetime.

how should proceed keep module , class named datetime?

put module package e.g., your_lib.datetime. should not use datetime name top-level module.

if on python 2 add @ top:

from __future__ import absolute_import 

to forbid implicit relative imports inside package. if 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 datetime import timedelta 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -