转换numpy。datetime64 to datetime对象,在numpy-1.8上表示UTC时间:
>>> from datetime import datetime
>>> import numpy as np
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> dt64 = np.datetime64(dt)
>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
>>> ts
1354650685.3624549
>>> datetime.utcfromtimestamp(ts)
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> np.__version__
'1.8.0.dev-7b75899'
上面的例子假设天真的datetime对象由np解释。datetime64作为UTC时间。
将datetime转换为np。Datetime64和返回(numpy-1.6):
>>> np.datetime64(datetime.utcnow()).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)
它对单个np都有效。对象和np.datetime64的numpy数组。
想想np。datetime64与np.int8、np.int16等相同,并应用相同的方法在Python对象(如int、datetime和相应的numpy对象)之间进行转换。
你的“讨厌的例子”是正确的:
>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__
'1.6.2' # current version available via pip install numpy
我可以在安装的numpy-1.8.0上重新生成long值:
pip install git+https://github.com/numpy/numpy.git#egg=numpy-dev
同样的例子:
>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
1025222400000000000L
>>> numpy.__version__
'1.8.0.dev-7b75899'
它返回long,因为对于numpy。datetime64类型.astype(datetime)等价于.astype(object),在numpy-1.8上返回Python整数(long)。
要获取datetime对象,可以:
>>> dt64.dtype
dtype('<M8[ns]')
>>> ns = 1e-9 # number of seconds in a nanosecond
>>> datetime.utcfromtimestamp(dt64.astype(int) * ns)
datetime.datetime(2002, 6, 28, 0, 0)
获取直接使用秒的datetime64:
>>> dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
>>> dt64.dtype
dtype('<M8[s]')
>>> datetime.utcfromtimestamp(dt64.astype(int))
datetime.datetime(2002, 6, 28, 0, 0)
numpy文档说datetime API是实验性的,在未来的numpy版本中可能会改变。