Getting the closest date to a given date

前端 未结 8 628
Happy的楠姐
Happy的楠姐 2020-12-03 08:50

Given this base date:

base_date = \"10/29 06:58 AM\"

I want to find a tuple within the list that contains the closest date to the bas

8条回答
  •  清歌不尽
    2020-12-03 09:09

    Linear search?

    import sys
    import time
    
    base_date = "10/29 06:58 AM"
    
    def str_to_my_time(my_str):
        return time.mktime(time.strptime(my_str, "%m/%d %I:%M %p")) 
                    # assume year 1900...
    
    base_dt = str_to_my_time(base_date)
    
    list_date = [('10/30 02:18 PM', '-103', '-107'), 
                 ('10/30 02:17 PM', '+100', '-110'),
                 ('10/29 02:15 AM', '-101', '-109')]
    
    
    best_delta = sys.maxint
    best_match = None
    
    for t in list_date:
        the_dt = str_to_my_time(t[0])
        delta_sec = the_dt - base_dt
        if (delta_sec >= 0) and (delta_sec < best_delta):
            best_delta = delta_sec
            best_match = t
    
    print best_match, best_delta
    

    Producing:

    ('10/30 02:17 PM', '+100', '-110') 112740.0
    

提交回复
热议问题