Python 在datetime子类中使用datetime.replace()
我想子类化Python 在datetime子类中使用datetime.replace(),python,datetime,subclass,Python,Datetime,Subclass,我想子类化datetime.datetime并添加一个属性ticks,以获取/设置次秒部分为65536(0x10000)的分数,而不是微秒。(这是为了模拟IEC 61375-1 TIMEDATE48数据类型,请参阅。) 我迄今为止的努力: import datetime class MyDateTime(datetime.datetime): def __new__(cls, *args, **kwargs): return super().__new__(cls,
datetime.datetime
并添加一个属性ticks
,以获取/设置次秒部分为65536(0x10000)的分数,而不是微秒。(这是为了模拟IEC 61375-1 TIMEDATE48数据类型,请参阅。)
我迄今为止的努力:
import datetime
class MyDateTime(datetime.datetime):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
@property
def ticks(self):
return int(self.microsecond / 1000000 * 0x10000)
@ticks.setter
def ticks(self, ticks_):
# self.microsecond = int(ticks_ / 0x10000 * 1000000) # attribute 'microsecond' is not writeable
self.replace(microsecond=int(ticks_ / 0x10000 * 1000000)) # replace() returns a new datetime object
# self = self.replace(microsecond=int(ticks_ / 0x10000 * 1000000)) # doesn't work either
由于我无法直接分配微秒
属性,因此我使用的是replace()
,如中所示。但这将返回一个新的datetime.datetime
对象,而不是操作self
。将self
指向此新对象也不起作用
在我的子类的ticks
属性中覆盖datetime.datetime.microsecond
的正确方法是什么?
在datetime子类的构造函数中传递时区时,我也偶然发现了它。是否有可能或建议以通用方式对
datetime.datetime
进行子类化?如果不是不可能的话,子类化内置程序通常是有问题的。建议您只定义自己的“datetime类”类。Python的输入并不严格,所以如果它足够像datetime
的话,你可能可以不必这样做。查找“duck typing”。@stovfl,如果我按照你的建议做的话,然后dt=MyDateTime(2019,12,20,微秒=123456);dt.ticks=(0x10000/2)
然后dt.microsecond
仍然是123456,而不是预期的500000(0.5s)。对我来说,isinstance(t,datetime.datetime)
是True
。Python 3.7。1@rikinet:选中我自己,属性dt.microsecond
返回self.\u microsecond
,但该属性在对象日期时间中不存在。因此,self.\u微秒=
创建一个不从属性使用的新属性。