Fix Python – Find oldest/youngest datetime object in a list

Question

Asked By – panosl

I’ve got a list of datetime objects, and I want to find the oldest or youngest one. Some of these dates might be in the future.

from datetime import datetime

datetime_list = [
    datetime(2009, 10, 12, 10, 10),
    datetime(2010, 10, 12, 10, 10),
    datetime(2010, 10, 12, 10, 10),
    datetime(2011, 10, 12, 10, 10), #future
    datetime(2012, 10, 12, 10, 10), #future
]

What’s the most optimal way to do so? I was thinking of comparing datetime.now() to each one of those.

Now we will see solution for issue: Find oldest/youngest datetime object in a list


Answer

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

This question is answered By – eumiro

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0