136

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.

panosl
  • 1,709
  • 2
  • 12
  • 15

5 Answers5

180

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • You mean oldest? (`Oldest before now`) – Bulgantamir Jun 28 '18 at 12:11
  • In Python 3, I think this is flawed. If I give this array ["April2020", "March2020"], min will give me "April2020" as if min will give most recent. However, if I give it ["April2020", "January2021", "March2020"], min will give me "April2020". I'm pretty sure min will give the alphabetical lowest which is not necessarily the most recent date. – ScottyBlades Apr 18 '20 at 04:49
  • 3
    @ScottyBlades that's because in your example your values are strings (which happen to represent a date, but are not actually `date` values), so they can only really be compared alphabetically. If you instead had an array of `date` or `datetime` values, they would be compared correctly. – Jordan Apr 29 '20 at 00:03
42

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

JoshD
  • 12,490
  • 3
  • 42
  • 53
19

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

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
8

have u tried this :

>>> from datetime import datetime as DT
>>> l =[]
>>> l.append(DT(1988,12,12))
>>> l.append(DT(1979,12,12))
>>> l.append(DT(1979,12,11))
>>> l.append(DT(2011,12,11))
>>> l.append(DT(2022,12,11))
>>> min(l)
datetime.datetime(1979, 12, 11, 0, 0)
>>> max(l)
datetime.datetime(2022, 12, 11, 0, 0)
jknair
  • 4,709
  • 1
  • 17
  • 20
-2

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Malik A. Rumi
  • 1,855
  • 4
  • 25
  • 36
  • 6
    According to these docs, datetime.min() returns the smallest representable datetime, not the minimum of a list of datetimes. – Daan Dec 23 '20 at 10:34