如何从numpy datetime64继承?例如,使用标准日期时间,我可以轻松地子类化:
import datetime as dt
class SubFromDateTime(dt.datetime):
def __new__(self):
return dt.datetime.__new__(self, 2012, 1, 1)
print type(SubFromDateTime())
>>>
<class '__main__.SubFromDateTime'>
但是,使用datetime64,以下内容始终返回datetime64参考,而不是我的课程…
from numpy import datetime64
class SubFromDT64(datetime64):
def __new__(self):
return datetime64.__new__(self, '20120101')
print type(SubFromDT64())
>>>
<type 'numpy.datetime64'>
我怎样才能解决这个问题?我基本上想为datetime64写一个简单的包装器,它使我可以添加自定义函数,例如使用简单的.Month()方法获取给定日期的月份.在上面的示例中,我可以轻松地添加方法,在下面的示例中,它将永远无法识别我的方法,并认为它是datetime64对象.
解决方法:
我结束了子类化ndarray的创建,它创建了datetime64数组.就我的目的而言,它就像是一种魅力.如果有人对这里的代码感兴趣:
import numpy as np
class Date64(np.ndarray):
def __new__(cls, data):
data = np.asarray(data, dtype='datetime64')
if (data.dtype != 'datetime64[D]'):
raise Exception('Unable to parse dates adequately to datetime64[D]: %s' % data)
obj = data.view(cls)
return obj
def Year(self):
return self.astype('datetime64[Y]').astype(int) + 1970
def Month(self):
return self.astype('datetime64[M]').astype(int) % 12 + 1
def Day(self):
return (self - self.astype('datetime64[M]') + 1).astype(int)
def ISO(self):
if (self.shape):
out = zip(self.Year(), self.Month(), self.Day())
iso = [ '%04d-%02d-%02d' % each for each in out ]
else:
iso = '%04d-%02d-%02d' % (self.Year(), self.Month(), self.Day())
return iso
def Export(self):
return self
def __array_finalize__(self, obj):
if obj is None:
return
if (__name__ == '__main__'):
a = [ dt.date(2013, 1, 1), '2012-03-01', '2012-07-02', '2012-01-03', '2012-01-04', '2011-01-05' ]
b = Date64(a)
print b
print b.ISO()