如何在一个列表中找到距给定值n分钟内的所有日期时间? [英] How can I find all datetimes in a list within n minutes of a given value?

查看:36
本文介绍了如何在一个列表中找到距给定值n分钟内的所有日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个时间列表(小时:分钟:秒格式),我一直在努力将list_a中的每个条目与list_b中的所有条目进行比较,以确定落入30分钟内的值:

list_a = ["10:26:42", "8:55:43", "7:34:11"]
list_b = ["10:49:20", "8:51:10", "10:34:35", "8:39:47", "7:11:49", "7:42:10"]

预期输出:

10:26:42 is within 30m of 10:49:20, 10:34:35
8:55:43 is within 30m of 8:51:10, 8:39:47
7:34:11 is within 30m of 7:11:49, 7:42:10

到目前为止,我一直在做的是:

import datetime

# Convert the Lists to Datetime Format

for data in list_a:
    convert = datetime.datetime.strptime(data,"%H:%M:%S")
    list_a_times.append(convert)

for data in list_b:
    convert = datetime.datetime.strptime(data,"%H:%M:%S")
    list_b_times.append(convert)

# Using a Value of List A, Find the Closest Value in List B

for data in list_a_times:
     closest_to_data = min(list_b_times, key=lambda d: abs(d - data))

     print(data, closest_to_data)

这种方法有效,但它只找到一个最接近的值!只要值在所需的30分钟或更短时间内,我如何操作min()函数来继续提供这些值?

推荐答案

IIUC,您想要比较所有组合,所以需要全部选中。

请阅读datetime/timedelta上的注释的答案末尾。

使用itertools.product

list_a = ['10:26:42', '8:55:43', '7:34:11']
list_b = ['10:49:20', '8:51:10', '10:34:35', '8:39:47', '7:11:49', '7:42:10']

import datetime
from itertools import product

str2time = lambda s: datetime.datetime.strptime(s, "%H:%M:%S")

for a,b in product(map(str2time, list_a), map(str2time, list_b)):
    if abs(a-b).total_seconds() <= 1800:
        print(f'{a:%H:%M:%S} is within 30m of {b:%H:%M:%S}')

输出:

10:26:42 is within 30m of 10:49:20
10:26:42 is within 30m of 10:34:35
08:55:43 is within 30m of 08:51:10
08:55:43 is within 30m of 08:39:47
07:34:11 is within 30m of 07:11:49
07:34:11 is within 30m of 07:42:10

使用嵌套的for循环:

import datetime

str2time = lambda s: datetime.datetime.strptime(s, "%H:%M:%S")

for a in map(str2time, list_a):
    start = f'{a:%H:%M:%S} is within 30m of'
    for b in map(str2time, list_b):
        if abs(a-b).total_seconds() <= 1800:
            print(f'{start} {b:%H:%M:%S}', end='')
            start = ','
    if start == ',':
        print()

输出:

10:26:42 is within 30m of 10:49:20, 10:34:35
08:55:43 is within 30m of 08:51:10, 08:39:47
07:34:11 is within 30m of 07:11:49, 07:42:10

datetime

备注 使用不带日期的datetime将默认为1900-01-01,这可能会在接近午夜时产生边缘效果。相反,您可以使用timedelta对象。在我的代码中,您需要将str2time函数更改为:

def str2time(s):
    h,m,s = map(int, s.split(':'))
    return datetime.timedelta(hours=h, minutes=m, seconds

并稍微更改代码以能够转换为字符串:

z = datetime.datetime(1900,1,1)

for a in map(str2time, list_a):
    start = f'{z+a:%H:%M:%S} is within 30m of'
    for b in map(str2time, list_b):
        if abs(a-b).total_seconds() <= 1800:
            print(f'{start} {z+b:%H:%M:%S}', end='')
            start = ','
    if start == ',':
        print()

这篇关于如何在一个列表中找到距给定值n分钟内的所有日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆