Getting the closest date to a given date

前端 未结 8 608
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:18

    This can be done using datetime module, which is able to parse date string into datetime object, which supports comparison and arithmetic with dates:

    from datetime import datetime
    
    # function for parsing strings using specific format
    get_datetime = lambda s: datetime.strptime(s, "%m/%d %I:%M %p")
    
    base = get_datetime(base_date)
    later = filter(lambda d: get_datetime(d[0]) > base, list_date)
    closest_date = min(later, key = lambda d: get_datetime(d[0]))
    

提交回复
热议问题