I need to have a method to easily create an instance of a datetime.datetime subclass, given an existing datetime.datetime() instance.
Say I have the following contrived example:
class SerializableDateTime(datetime):
def serialize(self):
return self.strftime('%Y-%m-%d %H:%M')
I'm using a class like this (but a bit more complex), to use in a SQLAlchemy model; you can tell SQLAlchemy to map a custom class to a supported DateTime column value with a TypeDecorator class; e.g.:
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
I can't use return SerializableDateTime(value) here because the default datetime.datetime.__new__() method doesn't accept a datetime.datetime() instance:
>>> 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)
Is there a shortcut that avoids having to copy value.year, value.month, etc. all the way down to the timezone into a constructor?