Skip to main content
 首页 » 编程设计

python之在给定日期时间之前查找列表中的最新日期时间

2025年05月04日17www_RR

我在 np.datetime64 中有两个日期时间列表格式。 (没有必要 - 可以是 unix 时间戳或 datetime.datetime )

当我遍历密集列表 ( times_dense ) 时,我想从 times_sparse 中获取时间最接近但小于times_dense的时间.我很糟糕 datetime所以我只是把它放在一起。

most_recent_time = None 
 
for time_d in times_dense: 
    for time_s in times_sparse: 
        # time_d is after time_s and time_s is after most_recent_time 
        if(time_d >= time_s and time_s > most_recent_time): 
            most_recent_time = time_s 
 
return most_recent_time 

有没有简单的方法来做到这一点?我的方法会奏效吗?它很笨重并且运行时间很长。解决此问题的最佳方法是什么?

PS. 我最初将这些放在 pandas 数据框中,但由于无法在数据框中找到解决方案而将其取出。如果这可以用于 pandas,那就更好了。

请您参考如下方法:

这是按照您描述的方式进行的时间比较。现在,我专注于重现您的情况,而不是使其达到最佳状态

制作两个日期数组:

In [434]: t1=np.array(np.random.randint(100,size=(10,)),dtype='datetime64[D]') 
 
In [435]: t2=np.array(np.random.randint(100,size=(10,)),dtype='datetime64[D]') 
 
In [436]: t1 
Out[436]:  
array(['1970-02-25', '1970-01-31', '1970-01-04', '1970-03-17', 
       '1970-03-17', '1970-01-02', '1970-02-09', '1970-04-05', 
       '1970-02-22', '1970-03-08'], dtype='datetime64[D]') 
 
In [437]: t2 
Out[437]:  
array(['1970-01-16', '1970-02-24', '1970-02-28', '1970-01-21', 
       '1970-03-08', '1970-03-22', '1970-02-02', '1970-02-12', 
       '1970-02-24', '1970-02-06'], dtype='datetime64[D]') 

开始日期:

In [438]: recent=np.datetime64(0,'D') 
 
In [439]: recent 
Out[439]: numpy.datetime64('1970-01-01') 

你的迭代:

In [440]: for td in t1: 
    for ts in t2: 
        if (td>=ts) and (ts>recent): 
            recent=ts 
   .....:              
 
In [441]: recent 
Out[441]: numpy.datetime64('1970-03-22') 

np.datetime64 可以很好地处理比较(和算术)。

具有 np.datetime64 值的

np.array 可以以与具有整数值的数组相同的方式使用

(对于不同的 t2):

In [458]: t2.max() 
Out[458]: numpy.datetime64('1970-04-05') 
 
In [459]: t2[np.argmax(t1>=t2[:,None],axis=0)] 
Out[459]:  
array(['1970-02-08', '1970-03-07', '1970-03-07', '1970-03-07', 
       '1970-03-07', '1970-03-07', '1970-02-08', '1970-03-07', 
       '1970-02-08', '1970-03-07'], dtype='datetime64[D]') 

像最后一个这样的表达式可能会重现您的迭代 - 但它需要调整。