在 Ubuntu 和 Windows 上都尝试过此操作
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'
然后编辑文件。只是为了测试替换了
isoformat
的
class date
方法的返回行
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,但是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'
那么,这是否应该像这样工作,还是必须做其他事情?
你走错了路。 尝试使用来自 datetime 模块对象的继承,尽管这并不完全是微不足道的。
import datetime
class MyDate(datetime.date):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
def isoformat(self):
return "%04d-%02d" % (self.year, self.month)
__str__ = isoformat
if __name__ == '__main__':
date = MyDate(1,2,3)
print(date)