user2854008
user2854008

Reputation: 1221

Python find the max date in a list which are no later than a given date

I want to compare a date string to a list of date strings, and find out the max date in the list which are no later than the date given.

date='2015-04-16'

dates=[str(int(date[:4])-1)+'-05-01'
    ,str(int(date[:4])-1)+'-09-01'
    ,str(int(date[:4])-1)+'-11-01'
    ,date[:4]+'-05-01'
    ,date[:4]+'-09-01'
    ,date[:4]+'-11-01']

The right output should be the third element in dates, which is '2014-11-01'.

Can anyone help me with this? Thanks!

Upvotes: 2

Views: 808

Answers (2)

John Wiseman
John Wiseman

Reputation: 3137

If your list is sorted (as in your example), you can do this very efficiently using Python's bisect module:

import bisect

date='2015-04-16'

dates=[str(int(date[:4])-1)+'-05-01'
    ,str(int(date[:4])-1)+'-09-01'
    ,str(int(date[:4])-1)+'-11-01'
    ,date[:4]+'-05-01'
    ,date[:4]+'-09-01'
    ,date[:4]+'-11-01']

i = bisect.bisect(dates, date)
# Subtract one from the insertion point to find the previous date.
print dates[i - 1]

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168616

Since you've used a lexicographically-ordered date format, you can compare the strings directly. Finding the maximum of a group of items is the job of max(). Choosing what items go in the group can be done by a generator expression.

date='2015-04-16'

dates=[str(int(date[:4])-1)+'-05-01'
    ,str(int(date[:4])-1)+'-09-01'
    ,str(int(date[:4])-1)+'-11-01'
    ,date[:4]+'-05-01'
    ,date[:4]+'-09-01'
    ,date[:4]+'-11-01']

print max(x for x in dates if x < date)

References:

Upvotes: 3

Related Questions