Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max date in python list

Tags:

python

date

list

I have an list:

a=[datetime.date(2010,10,20),1,4,datetime.date(2013,10,20)]

As you can see the list contains different types of elements. How can I get the max date within the list?

My attempt:

from datetime import datetime
b=datetime.max(a)
print b
like image 650
user3561251 Avatar asked Feb 04 '15 02:02

user3561251


2 Answers

For guidence Find oldest/youngest datetime object in a list

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(2015, 2, 12, 10, 10), # future
    datetime(2016, 2, 12, 10, 10), # future
]
oldest = min(datetime_list)
youngest = max(datetime_list)

The prior post has filter to exclude future events

like image 135
Nodak Avatar answered Sep 19 '22 06:09

Nodak


First, keeping dates and integers together in the same list -- except as an intermediate step -- can be a sign your data structure isn't appropriate. That said, you can easily take the max only of the dates by using a generator expression:

>>> import datetime
>>> a=[datetime.date(2010,10,20),1,4,datetime.date(2013,10,20)]
>>> max(d for d in a if isinstance(d, datetime.date))
datetime.date(2013, 10, 20)
like image 33
DSM Avatar answered Sep 23 '22 06:09

DSM