Getting the closest date to a given date

前端 未结 8 632
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:07

    You can consider putting the dates list into a Pandas index and then use 'truncate' or 'get_loc' function.

    import pandas as pd
    
    ##Initial inputs
    list_date = [('10/30 02:18 PM', '-103', '-107'),('10/29 02:15 AM', '-101', '-109') , ('10/30 02:17 PM', '+100', '-110'), \
                 ]  # reordered to show the method is input order insensitive
    base_date = "10/29 06:58 AM"
    
    
    ##Make a data frame with data
    df=pd.DataFrame(list_date)
    df.columns=['date','val1','val2']
    dateIndex=pd.to_datetime(df['date'], format='%m/%d %I:%M %p')
    df=df.set_index(dateIndex) 
    df=df.sort_index(ascending=False) #earliest comes on top 
    
    ##Find the result
    base_dateObj=pd.to_datetime(base_date, format='%m/%d %I:%M %p')
    result=df.truncate(after=base_dateObj).iloc[-1]  #take the bottom value, or the 1st after the base date
    (result['date'],result['val1'], result['val2']) # result is ('10/30 02:17 PM', '+100', '-110')
    

    Reference: this link

提交回复
热议问题