Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find oldest/youngest datetime object in a list

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.

like image 817
panosl Avatar asked Oct 13 '10 10:10

panosl


3 Answers

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)
like image 102
eumiro Avatar answered Nov 19 '22 08:11

eumiro


Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

like image 22
JoshD Avatar answered Nov 19 '22 08:11

JoshD


Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

like image 19
Gabi Purcaru Avatar answered Nov 19 '22 08:11

Gabi Purcaru