代码之家  ›  专栏  ›  技术社区  ›  Snowfire777

时间列表上的秒操作[关闭]

  •  -1
  • Snowfire777  · 技术社区  · 8 年前

    我正在处理格式为%H:%m:%S的时间列表。f:

    ['13:48:25.195', '13:48:25.994', '13:48:26.995', '13:48:27.995', '13:48:28.995', '13:48:29.995', '13:48:30.995', '13:48:31.995', '13:48:32.995', '13:48:33.995', '13:48:35.001', '13:48:35.995', '13:48:36.995', '13:48:37.995', '13:48:38.995', '13:48:39.995', '13:48:40.995', '13:48:41.995', '13:48:42.995', '13:48:43.995', '13:48:44.995', '13:48:45.995', '13:48:46.995', '13:48:47.995', '13:48:48.995', '13:48:49.995', '13:48:50.995', '13:48:51.995', '13:48:52.995', '13:48:53.995', '13:48:54.995', '13:48:55.995', '13:48:56.995', '13:48:57.995', '13:48:58.995', '13:48:59.995']

    设置函数以查找列表中的每个项目后。我想要一个ceratin时间戳找到 t-1型 t+1 ,基于秒。

    1 回复  |  直到 8 年前
        1
  •  1
  •   sciroccorics    8 年前

    这应该可以:

    def adjust(h,m,s):
        if s > 59: m, s = m+1, s-60
        if s <  0: m, s = m-1, s+60
        if m > 59: h, m = h+1, m-60
        if m <  0: h, m = h-1, m+60
        return "%02d:%02d:%02d" % (h, m, s) // old-style formating
      # return f"{h:02}:{m:02}:{s:02}"      // new-style formating (Python 3.6+)
    
    
    for t in ('13:48:43.995', '13:59:59.295', '8:00:00'):
        h, m, s = [round(float(x)) for x in t.split(':')]
        nearest_sec = adjust(h, m, s)
        add_one_sec = adjust(h, m, s+1)
        sub_one_sec = adjust(h, m, s-1)
        print(nearest_sec, '-->', add_one_sec, sub_one_sec)
    

    以下是生成的输出:

    13:48:44 --> 13:48:45 13:48:43
    13:59:59 --> 14:00:00 13:59:58
    08:00:00 --> 08:00:01 07:59:59
    

    请注意,结果不能跨越午夜,因为您的时间戳不包括天。。。