如何从numpy.datetime64或numpy.datetime_获取UNIX时间?如何从numpy.datetime64获取unix时间戳
正如例如:
np.datetime_('2012-08-08 13:37:00')
如何从numpy.datetime64或numpy.datetime_获取UNIX时间?如何从numpy.datetime64获取unix时间戳
正如例如:
np.datetime_('2012-08-08 13:37:00')
对于numpy 1.6.1与1.7,我得到np.datetime64('now')
的值的结果不一致。
这适用于以下两者:
>>> import datetime
>>> import numpy as np
>>> now = np.datetime64(datetime.datetime.now())
>>> (now.astype('uint64')/1e6).astype('uint32')
1344447810
def get_unixtime(time):
return (time.astype(np.int64)/1e6).astype(np.int64)
get_unixtime(np.datetime64('now'))
似乎回到了UNIX时间戳,我只用了几个日期检查。
numpy的datetime64具有可变的单元:
从official doc提取:
用于内部存储的单元自动地从所述串的形式选择,并且可以是日期单位或时间单位。日期单位是年('Y'),月('M'),星期('W')和日期('D'),而时间单位是小时('h'),分钟('m' ),秒('s'),毫秒('ms')和一些额外的SI前缀以秒为单位。
所以,首先我们需要使用D型检查当前的单位,例如:
>>> now = np.datetime64(datetime.datetime.now())
>>> now.dtype
# for ns unit, use:
dtype('<M8[ns]')
now.astype('int64')/1e9, dtype='int32'
# for us unit, use:
dtype('<M8[us]')
now.astype('int64')/1e6, dtype='int32'
# for ms unit, use:
dtype('<M8[ms]')
now.astype('int64')/1e3, dtype='int32'
等等....
为了占单位,我想你需要做的是这样的:
def get_unixtime(dt64):
return dt64.astype('datetime64[s]').astype('int')
注意,将其转换为“秒”(在[s]
)转换成整数之前秒。这适用于NumPy 1.12.1。
根据文档datetime64在[numpy 1.6]中不是很可靠(http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#differences-between-1-6-and- 1-7-日期时间)。即使是1.7,api也是实验性的。所以我不确定,如果你会在不同的平台和体系结构(64位?)上获得一致的结果。有关更多信息,请参阅[pandas 0.8发行说明](http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#potential-porting-issues-for-pandas-0-7-3-用户)。所以不确定,如果在numpy 1.6上使用datetime64是个不错的选择。 – bmu 2012-08-08 16:49:43
是啊,因为代码本身将是实验性的,只能驻留在一台机器上,如果它一次正常工作,它可以被认为是可行的? – SlimJim 2012-08-08 21:22:50
好的,但你应该在你的问题中指定numpy的版本,平台和体系结构(也许是Python版本,2和3的结果相同?)。否则可能会导致读者误解。 – bmu 2012-08-09 08:47:22