[python] 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.

This question is related to python datetime compare

The answer is


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)

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)


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


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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java