我尝试使用monkey patching实现解决方案,但遇到错误:TypeError: can't set attributes of built-in/extension type 'datetime.datetime'
这在datetime.datetime.millisecond = millisecond和GvR's ^{}中发生。
也许datetime.so不能被猴子修补。如果这是真的,那么您可能需要考虑:import datetime
class DateTime(datetime.datetime):
@property
def millisecond(self):
return self.microsecond/1000.0
def __add__(self,other):
result=super(DateTime,self).__add__(other)
result=DateTime(result.year,
result.month,
result.day,
result.hour,
result.minute,
result.second,
result.microsecond,
result.tzinfo)
return result
__radd__=__add__
d = DateTime(2010, 07, 11, microsecond=3000)
print d.millisecond
# 3.0
delta = datetime.timedelta(hours=4)
newd = d + delta
print newd.millisecond
# 3.0
# This uses __radd__
newd = delta + d
print newd.millisecond
# 3.0