是否可以通过int数组将DatetimeIndex转换为datetime64 [s]数组而不用除以1e9?
以下代码提供了一个整数numpy数组,但我必须除以1e9
才能从纳秒转换为秒。
是否可以进行此旅程(DatetimeIndex,int numpy数组,最后是datetime64 [s] numpy数组)而无需除以1e9
?
import pandas as pd
import numpy as np
start = pd.Timestamp('2015-07-01')
end = pd.Timestamp('2015-07-05')
t = np.linspace(start.value, end.value, 5)
datetimeIndex = pd.to_datetime(t)
'''type: DatetimeIndex'''
datetimeIndex
Out[2]:
DatetimeIndex(['2015-07-01', '2015-07-02', '2015-07-03', '2015-07-04',
'2015-07-05'],
dtype='datetime64[ns]', freq=None)
datetimeIndexAs10e9int = datetimeIndex.values.astype(np.int64)
'''datetimeIndexAs10e9int - like [1435708800000000000]'''
datetimeIndexAs10e9int
Out[3]:
array([1435708800000000000, 1435795200000000000, 1435881600000000000,
1435968000000000000, 1436054400000000000])
datetime = (1/1e9*datetimeIndexAs10e9int).astype(np.float).astype('datetime64[s]')
datetime
Out[4]:
array(['2015-07-01T00:00:00', '2015-07-02T00:00:00',
'2015-07-03T00:00:00', '2015-07-04T00:00:00',
'2015-07-05T00:00:00'], dtype='datetime64[s]')
答案 0 :(得分:1)
我认为您可以通过修改代码来实现。改用astype('datetime64 [s]')。
datetimeIndexAs10e9int = datetimeIndex.values.astype('datetime64[s]')