如何高效获取和索引基于小时数的日期和时间

2024-04-25 18:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个由一年中所有小时数组成的数组,例如

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

下面的代码可以处理从一年中的小时数索引一天

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')

但是,如果我想把一天从2012-09-01索引到2012-09-05,这意味着ntim=120,我不知道如何使np.where()工作。你知道吗

有没有什么有效的方法可以根据一年中的小时数来获取datetime和date,然后用np.where("2012-09-05">=index_date>="2012-09-01")之类的方法进行索引

任何帮助都将不胜感激。你知道吗


Tags: ofnewfordatetimedateindextimenp
1条回答
网友
1楼 · 发布于 2024-04-25 18:55:28

考虑使用numpy的内置datetime64timedelta64

>>> 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]')

或者反过来说:

>>> 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])

相关问题 更多 >