Skip to content Skip to sidebar Skip to footer

Finding Min/max Date With List Comprehension In Python

So I have this list: snapshots = ['2014-04-05', '2014-04-06', '2014-04-07', '2014-04-08', '2014-04-09'] I would like to find the earliest date usin

Solution 1:

Just use min() or max() to find the earliest or latest dates:

earliest_date = min(snapshots)
lastest_date = max(snapshots)

Of course, if your list of dates is already sorted, use:

earliest_date = snapshots[0]
lastest_date = snapshots[-1]

Demo:

>>>snapshots = ['2014-04-05',...'2014-04-06',...'2014-04-07',...'2014-04-08',...'2014-04-09']>>>min(snapshots)
'2014-04-05'

Generally speaking, a list comprehension should only be used to build lists, not as a general loop tool. That's what for loops are for, really.

Solution 2:

>>> snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

>>> min(snapshots)
2014-04-05

You can use the min function.

However, this assumes that your date is formatted YYYY-MM-DD, because you have strings in your list.

Solution 3:

If you have any issue while sorting the list you can convert the list elements to date and find the max/min of it

from dateutil import parser
snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

snapshots = [parser.parse(i).date() for i in snapshots ]

max_date = max(snapshots )
min_date = min(snapshots )
print(max_date)
print(min_date)

Post a Comment for "Finding Min/max Date With List Comprehension In Python"