如何从numpy.datetime64或numpy.datetime_获取UNIX时间?
例如:
np.datetime_('2012-08-08 13:37:00')
Run Code Online (Sandbox Code Playgroud)
为了说明单位,我认为您需要执行以下操作:
def get_unixtime(dt64):
return dt64.astype('datetime64[s]').astype('int')
Run Code Online (Sandbox Code Playgroud)
请注意,[s]在转换为整数之前,这将转换为“秒”()。这适用于NumPy 1.12.1。
小智 7
我想发布我发现的解决方案,我认为它可能比转换为 uint 更好一点,因为我觉得类型转换可能存在问题。
>>> import numpy as np
>>> now = np.datetime64('now')
>>> ux_time = now.astype(np.timedelta64) / np.timedelta64(1, 'ms')
Run Code Online (Sandbox Code Playgroud)
我觉得这个解决方案更好一点,因为它允许你选择你的 unix 时间单位。对于我正在开发的项目,我们使用“ms”,但如果需要,您可以指定不同的单位。
此外,这还允许使用 numpy 将 datetime64 数组转换为 timedelta64:
>>> date_time_array.astype(np.timedelta64) / np.timedelta64(1, 'ms')
Run Code Online (Sandbox Code Playgroud)
我用它将从 pandas 获取的 np.datetime64 列转换为 unixtime 数组
小智 6
numpy datetime64具有可变单位:
摘录自官方文件:
内部存储单位是从字符串形式中自动选择的,可以是日期单位或时间单位。日期单位是年('Y'),月('M'),周('W')和天('D'),而时间单位是小时('h'),分钟('m' ),秒(“ s”),毫秒(“ ms”)和一些其他基于SI前缀秒的单位。
因此,首先我们需要使用dtype检查当前单位,例如:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
等等....
对于np.datetime64('now')numpy 1.6.1与1.7 的值,我得到的结果不一致。
这对两个都起作用:
>>> import datetime
>>> import numpy as np
>>> now = np.datetime64(datetime.datetime.now())
>>> (now.astype('uint64') / 1e6).astype('uint32')
1344447810
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14122 次 |
| 最近记录: |