首页 > 解决方案 > 可以从现有日期时间实例创建的自定义日期时间子类?

问题描述

datetime.datetime在给定现有实例的情况下,我需要一种方法来轻松创建子类的datetime.datetime()实例。

假设我有以下人为的例子:

class SerializableDateTime(datetime):
    def serialize(self):
        return self.strftime('%Y-%m-%d %H:%M')

我正在使用这样的类(但有点复杂),用于 SQLAlchemy 模型;您可以告诉 SQLAlchemy 将自定义类映射到具有类的受支持的DateTime值;例如:TypeDecorator

class MyDateTime(types.TypeDecorator):
    impl = types.DateTime

    def process_bind_param(self, value, dialect):
        # from custom type to the SQLAlchemy type compatible with impl
        # a datetime subclass is fine here, no need to convert
        return value

    def process_result_value(self, value, dialect):
        # from SQLAlchemy type to custom type
        # is there a way have this work without accessing a lot of attributes each time?
        return SerializableDateTime(value)   # doesn't work

我不能return SerializableDateTime(value)在这里使用,因为默认datetime.datetime.__new__()方法不接受datetime.datetime()实例:

>>> value = datetime.now()
>>> SerializableDateTime(value)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type datetime.datetime)

是否有一种快捷方式可以避免将 , 等一直复制value.yearvalue.month时区到构造函数中?

标签: pythondatetimeinheritancepython-datetime

解决方案


尽管您可以为您的子类提供一个__new__检测单个datetime.datetime实例然后在那里进行所有复制的方法,但实际上我会为该类提供一个 classmethod 来处理这种情况,因此您的 SQLAlchemy 代码如下所示:

return SerializableDateTime.from_datetime(value)

我们可以利用该类已经实现的pickle支持;datetime.datetime()类型实现了钩子__reduce_ex__通常建立在更高级别的方法上__getnewargs__datetime.datetime()比如通过将元组应用回您的新类型来获得相同的状态。该方法可以通过 pickle 协议改变输出,但只要您传入,您就可以保证获得完整支持的值范围。datetime.datetimeargsargs__reduce_ex__pickle.HIGHEST_PROTOCOL

args组由一个或两个值组成,第二个是时区:

>>> from pickle import HIGHEST_PROTOCOL
>>> value = datetime.now()
>>> value.__reduce_ex__(HIGHEST_PROTOCOL)
(<class 'datetime.datetime'>, (b'\x07\xe2\n\x1f\x12\x06\x05\rd\x8f',))
>>> datetime.utcnow().astimezone(timezone.utc).__reduce_ex__(value.__reduce_ex__(HIGHEST_PROTOCOL))
(<class 'datetime.datetime'>, (b'\x07\xe2\n\x1f\x12\x08\x14\n\xccH', datetime.timezone.utc))

args元组中的第一个bytes值是一个表示对象所有属性的值(时区除外),并且构造函数datetime接受相同的字节值(加上一个可选的时区):

>>> datetime(b'\x07\xe2\n\x1f\x12\x06\x05\rd\x8f') == value
True

由于您的子类接受相同的参数,您可以使用args元组创建一个副本;我们可以通过断言它仍然是我们的父类来使用第一个值来防止未来 Python 版本的变化:

from pickle import HIGHEST_PROTOCOL

class SerializableDateTime(datetime):
    @classmethod
    def from_datetime(cls, dt):
        """Create a SerializableDateTime instance from a datetime.datetime object"""
        # (ab)use datetime pickle support to copy state across
        factory, args = dt.__reduce_ex__(HIGHEST_PROTOCOL)
        assert issubclass(cls, factory)
        return cls(*args)

    def serialize(self):
        return self.strftime('%Y-%m-%d %H:%M')

这使您可以创建子类的实例作为副本:

>>> SerializableDateTime.from_datetime(datetime.now())
SerializableDateTime(2018, 10, 31, 18, 13, 2, 617875)
>>> SerializableDateTime.from_datetime(datetime.utcnow().astimezone(timezone.utc))
SerializableDateTime(2018, 10, 31, 18, 13, 22, 782185, tzinfo=datetime.timezone.utc)

虽然使用 pickle钩子可能看起来有些 hackish,但它也是用于使用模块创建实例__reduce_ex__副本的实际协议,并且通过使用您可以确保复制所有相关状态,无论您使用的 Python 版本是什么。datetime.datetimecopy__reduce_ex__(HIGHEST_PROTOCOL)


推荐阅读