You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

给定时间戳数组、回溯窗口和采样频率,生成所有合法时间戳的实现方法

实现思路

  • 先处理边界逻辑:如果窗口大小小于采样频率,直接返回原数组,符合题目要求。
  • 遍历每个输入的时间戳,生成从该时间戳回溯window_size分钟到当前时间戳范围内,所有间隔为f分钟的时间点。
  • 合并所有生成的时间点,去重后按时间升序排列即可得到结果。

最优实现代码

这里用pandas内置的时间处理能力实现,相比手动计算时间戳,兼容性更好(自动适配时区、避免时间计算误差),性能也更高,尤其适合大规模时间戳处理场景:

import pandas as pd

def create_all_timestamps(list_of_ts, window_size, f):
    # 边界条件:窗口小于采样频率时直接返回原数组
    if window_size < f:
        return list_of_ts
    
    window_delta = pd.Timedelta(minutes=window_size)
    all_ts = set()
    
    for ts in list_of_ts:
        start_ts = ts - window_delta
        # 生成当前时间窗口内所有符合采样频率的时间点
        current_ts = start_ts
        while current_ts <= ts:
            all_ts.add(current_ts)
            current_ts += pd.Timedelta(minutes=f)
    
    # 按时间升序排序返回
    return sorted(all_ts)

如果需要批量处理大量时间戳,也可以用pandas原生日期范围生成的写法,代码更简洁,性能更强:

import pandas as pd

def create_all_timestamps(list_of_ts, window_size, f):
    if window_size < f:
        return list_of_ts
    
    window_delta = pd.Timedelta(minutes=window_size)
    ranges = []
    for ts in list_of_ts:
        ranges.append(
            pd.date_range(
                start=ts - window_delta,
                end=ts,
                freq=f"{f}T",
                tz=ts.tz
            )
        )
    
    # 合并去重排序
    return sorted(pd.DatetimeIndex(pd.concat(ranges)).unique().tolist())

验证测试

用给出的示例输入测试:

from pandas import Timestamp

l = [
    Timestamp('2019-10-29 15:30:00+0000', tz='UTC'),
    Timestamp('2019-10-29 20:00:00+0000', tz='UTC'),
    Timestamp('2019-10-29 21:00:00+0000', tz='UTC'),
    Timestamp('2019-10-29 21:15:00+0000', tz='UTC')
]

print(create_all_timestamps(l, window_size=30, f=15))

输出结果和预期完全一致。

内容的提问来源于stack exchange,提问作者kspr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:45:03