Allen Zhang
Allen Zhang

Reputation: 121

How to efficiently acquire and index the datetime and date based on the number of hour in a year

Suppose that I have a array composed of all the number of hour in a year, e.g.

 np.arange(8760)
 Out[5]: array([   0,    1,    2, ..., 8757, 8758, 8759])

And the following code can deal with indexing a day from the number of hour in a year,

year  = 2012
month = 1
day   = 1
fmt ='%Y-%m-%d_%H:%M:%S'
day0 = datetime.datetime(year,month,day)
new_time = []
index_date = []
time_list=(np.arange(8760)).tolist()
####actually the timelist is a column of other array
for hour in time_list:

    delta = datetime.timedelta(hours=hour)

    out_date = datetime.datetime.strftime(day0+delta,fmt)
    new_time.append(out_date)

    for_index_date = datetime.datetime.strftime(day0 + delta, "%Y-%m-%d")
    index_date.append(for_index_date)

new_time = np.array(new_time)   #for Times of ncfile
index_date=np.array(index_date)  #for indexing of days

ntim  = 24  ## 1day = 24 hour
### I want to index multiple days
index = np.where(index_date=="2012-09-01")

new_time=new_time[index]
Times = np.zeros((ntim,19),dtype="|S1")
Times[:]=new_time.view('U1').reshape(new_time.size, -1).astype('S1')

However,if I want to index the day from 2012-09-01to 2012-09-05,which means ntim=120, I don't know how to make np.where() work.

Is there any efficient method to acquire the datetime and date based on the number of hour in a year, and then to index with something like np.where("2012-09-05">=index_date>="2012-09-01")

Any help would be appreciated.

Upvotes: 0

Views: 155

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53079

Consider using numpy's inbuilt datetime64 and timedelta64:

>>> dates = np.datetime64('2012', 'Y') + np.arange(366*24).astype('m8[h]')
>>> dates
array(['2012-01-01T00', '2012-01-01T01', '2012-01-01T02', ...,
       '2012-12-31T21', '2012-12-31T22', '2012-12-31T23'],
      dtype='datetime64[h]')
>>> 
>>> indices = np.where((dates.astype('M8[D]') >= np.datetime64('2012-09-01')) & (dates.astype('M8[D]') <= np.datetime64('2012-09-05')))
>>> dates[indices]
array(['2012-09-01T00', '2012-09-01T01', '2012-09-01T02', '2012-09-01T03', ...,
       '2012-09-05T20', '2012-09-05T21', '2012-09-05T22', '2012-09-05T23'],
      dtype='datetime64[h]')

Or go the other way round:

>>> times = np.arange(np.datetime64('2012-09-01'), np.datetime64('2012-09-06'), np.timedelta64(1, 'h'))
>>> indices = (times - np.datetime64('2012-01-01')).astype(int)
>>> indices
array([5856, 5857, 5858, 5859, 5860, 5861, 5862, 5863, 5864, 5865, 5866,
       5867, 5868, 5869, 5870, 5871, 5872, 5873, 5874, 5875, 5876, 5877, ...,
       5955, 5956, 5957, 5958, 5959, 5960, 5961, 5962, 5963, 5964, 5965,
       5966, 5967, 5968, 5969, 5970, 5971, 5972, 5973, 5974, 5975])

Upvotes: 1

Related Questions