Find oldest/youngest datetime object in a list

PythonDatetimeCompare

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

Oldest:

oldest = min(datetimes)

Youngest before now:

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

Solution 2 - Python

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

Solution 3 - Python

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

Solution 4 - Python

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)

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpanoslView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonJoshDView Answer on Stackoverflow
Solution 3 - PythonGabi PurcaruView Answer on Stackoverflow
Solution 4 - PythonjknairView Answer on Stackoverflow
Solution 5 - PythonMalik A. RumiView Answer on Stackoverflow