user11509999
user11509999

Reputation:

Python Identifying most recent time(datetime) from a list?

I have two lists time_list with datetime and name_list with names mapped to each other respectively.

    time_list = [datetime.datetime(2020, 3, 28, 18, 49, 36, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 54, 53, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 19, 5, 28, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 59, 56, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 55, 42, tzinfo=tzutc())]


    name_list = [a,b,c,d,e]

How to find the which name_list has the most recent time in the time_list ?

In above example: time_list[2] has the most recent w.r.t name_list[2]

Expected output:

        most_recent_name_list = ['c']

Upvotes: 0

Views: 125

Answers (2)

A.B
A.B

Reputation: 20445

You can use sorted function and pass a range equal to length of original list as index, for keys, you can pas dates as key and perform reverse sort like following to get original indexes for sorted dates and use those index to get latest date from other list

sorted_list = sorted(range(len(time_list)),key=time_list.__getitem__,reverse=True)

and you can get index of sorted as

name_list[sorted_list[0]]

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24233

zip the two lists, this will give you tuples (date, name). Take the max of these tuples (they will be sorted by date first, then by name) and extract the name from the max:

import datetime
from dateutil.tz import tzutc

time_list = [datetime.datetime(2020, 3, 28, 18, 49, 36, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 54, 53, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 19, 5, 28, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 59, 56, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 55, 42, tzinfo=tzutc())]


name_list = ['a', 'b', 'c', 'd', 'e']

max(zip(time_list, name_list))[1]
#'c'

Upvotes: 1

Related Questions