def add_time(df, stim_dict, stimulus_timestamps):
    """
    add_time(df, stim_dict, stimulus_timestamps)

    Updates dataframe with time columns.

    Arguments:
        df (pandas): stimulus dataframe.
        stim_dict (dict): experiment stim dictionary, loaded from pickle
        stimulus_timestamps (1D array): timem stamps for each stimulus frames.

    Returns:
        df (pandas): updated stimulus table with time.
    """

    df = df.copy()

    df = df.sort_values("start_frame_twop").reset_index(drop=True)

    df["start_time_sec"] = stimulus_timestamps[
        df["start_frame_stim"].values.astype(int)
    ]

    non_final = range(0, len(df) - 1)
    df.loc[non_final, "stop_time_sec"] = stimulus_timestamps[
        df["stop_frame_stim"].values[:-1].astype(int)
    ]

    # final line
    final_row = len(df) - 1
    last_duration = (
        df.loc[final_row, "stop_frame_stim"] - 
        df.loc[final_row, "start_frame_stim"]
    ) / stim_dict["fps"]
    df.loc[final_row, "stop_time_sec"] = \
        df.loc[final_row, "start_time_sec"] + last_duration

    df["duration_sec"] = df["stop_time_sec"] - df["start_time_sec"]

    return df