user7468395
user7468395

Reputation: 1349

Conversion from DatetimeIndex to datetime64[s] via int without dividing by 1e9 possible?

Is it possible to convert from a DatetimeIndex to datetime64[s] array via int array without dividing by 1e9?

The following code delivers an int numpy array, but I have to divide by 1e9 to get from nanoseconds to seconds.

Is it possible to take this journey (DatetimeIndex, int numpy array, and finally datetime64[s] numpy array) without the dividing by 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]')

Upvotes: 1

Views: 604

Answers (1)

Loochie
Loochie

Reputation: 2472

I think you can do it by modifying your code. Use astype('datetime64[s]') instead.

datetimeIndexAs10e9int = datetimeIndex.values.astype('datetime64[s]')

Upvotes: 1

Related Questions