修改Python内置datetime模块未生效,是否需额外操作?
问题:修改datetime模块的date.isoformat方法后不生效?
我在Ubuntu和Windows系统的Python 3.8.10中做了如下操作:
- 找到datetime模块的文件路径:
Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:34:34) [MSC v.1928 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> datetime.__file__ 'C:\\Program Files\\python3810\\lib\\datetime.py'
- 修改
datetime.py中date类的isoformat方法,注释原返回语句,替换为仅返回年和月的格式:
class date: ... def isoformat(self): """Return the date formatted according to ISO. This is 'YYYY-MM-DD'. References: - http://www.w3.org/TR/NOTE-datetime - http://www.cl.cam.ac.uk/~mgk25/iso-time.html """ # return "%04d-%02d-%02d" % (self._year, self._month, self._day) return "%04d-%02d" % (self._year, self._month) __str__ = isoformat
- 重启Python Shell后测试,发现调用date对象的
__str__方法仍返回原格式:
Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:34:34) [MSC v.1928 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> d = datetime.date.today() >>> d datetime.date(2023, 11, 16) >>> d.__str__() '2023-11-16'
想问这种修改本应生效吗?还是需要执行其他操作?
解答
你的修改不会生效,核心原因是:Python的datetime模块核心逻辑是用C语言实现的,你找到的datetime.py只是一个辅助性的纯Python文件,实际运行时Python会优先加载底层的C扩展模块(Windows下为_datetime.pyd,Linux下为类似_datetime.cpython-38-x86_64-linux-gnu.so的文件),所以修改纯Python文件根本不会影响实际运行的代码。
绝对不要修改标准库文件——这会导致环境不稳定,且Python版本更新后修改会直接丢失。推荐用以下两种合法方式实现需求:
方式1:猴子补丁(动态替换方法)
在自己的代码中直接替换datetime.date的目标方法:
import datetime def custom_isoformat(self): return f"{self._year:04d}-{self._month:02d}" # 替换原方法 datetime.date.isoformat = custom_isoformat datetime.date.__str__ = custom_isoformat # 测试 d = datetime.date.today() print(d.__str__()) # 输出类似 2023-11 的格式
方式2:子类继承
自定义继承自datetime.date的子类,重写目标方法:
import datetime class CustomDate(datetime.date): def isoformat(self): return f"{self._year:04d}-{self._month:02d}" __str__ = isoformat # 使用子类创建日期对象 d = CustomDate.today() print(d) # 输出类似 2023-11 的格式
内容的提问来源于stack exchange,提问作者edvard_munch
相关产品推荐
相关产品推荐

