比较小时和分钟并找到与当前时间最接近的小时

问题描述 投票:0回答:1

Я хочу сравнить список часов 和 минут с текущем временем 和 найти ближайший час 和 минуты 和з списка。 Помогите реализовать?

у меня есть алгоритм только для даты, а как сделать тоже самое для моего вопроса

алгоритм:

日期列表 = ['2025-02-10', '2025-01-13', '2025-02-8'] datetime_list = [datetime.strptime(date, "%Y-%m-%d") for date_list 中的日期]

今天 = datetime.today()

date_diffs = [datetime_list 中日期的绝对值(日期 - 今天)]

closest_date = date_list[date_diffs.index(min(date_diffs))

time
1个回答
0
投票

以下代码将处理表示目标时间(小时、分钟)的元组列表,并以元组(小时、分钟)的形式返回最接近的目标时间。

import datetime

def find_nearest_time(target_times):
    # Get the current time
    current_time = datetime.datetime.now()
    current_hour = current_time.hour
    current_minute = current_time.minute
    
    # Calculate current time in minutes from midnight
    current_time_minutes = current_hour * 60 + current_minute
    
    # Initialize variables to track the nearest time
    nearest_time = None
    min_difference = float('inf')  # Start with a large difference
    
    # Iterate over the list of target times
    for hour, minute in target_times:
        # Calculate the target time in minutes from midnight
        target_time_minutes = hour * 60 + minute
        
        # Calculate the absolute difference in minutes
        # between target time and current time
        difference = abs(target_time_minutes - current_time_minutes)
        
        # Update nearest time if this target time is closer
        if difference < min_difference:
            min_difference = difference
            nearest_time = (hour, minute)
    
    return nearest_time
© www.soinside.com 2019 - 2024. All rights reserved.