Get min and max dates
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Dec 8 00:16:50 EST 2016
On Thursday 08 December 2016 03:15, DFS wrote:
> dts= ['10-Mar-1998',
> '20-Aug-1997',
> '06-Sep-2009',
> '23-Jan-2010',
> '12-Feb-2010',
> '05-Nov-2010',
> '03-Sep-2009',
> '07-Nov-2014',
> '08-Mar-2013']
>
> Of course, the naive:
> min(dates) = '03-Sep-2009'
> max(dates) = '23-Jan-2010'
> is wrong.
>
> Not wanting to use any date parsing libraries, I came up with:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
That's where you have gone wrong. By not using a date parsing library which
works and has been tested, you have to write your own dodgy and possibly buggy
parsing routine yourself.
Why reinvent the wheel?
> ========================================================================
> m=[('Dec','12'),('Nov','11'),('Oct','10'),('Sep','09'),
> ('Aug','08'),('Jul','07'),('Jun','06'),('May','05'),
> ('Apr','04'),('Mar','03'),('Feb','02'),('Jan','01')]
>
> #create new list with properly sortable date (YYYYMMDD)
> dts2 = []
> for d in dts:
> dts2.append((d[-4:]+dict(m)[d[3:6]]+d[:2],d))
Why do you convert m into a dict each and every time through the loop? If you
have a million items, you convert m to a dict a million times, and then throw
away the dict a million times. And then you'll complain that Python is slow...
m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
There you go, fixed that.
As for the rest, I haven't bothered to check your code. But here's a much
simpler, more Pythonic, way:
def date_to_seconds(string):
return time.mktime(time.strptime(string, '%d-%b-%Y'))
min(dts, key=date_to_seconds) # returns '20-Aug-1997'
max(dts, key=date_to_seconds) # returns '07-Nov-2014'
Works for at least Python 3.3 or better.
The best part of this is that you can now support any time format you like,
just by changing the format string '%d-%b-%Y'.
--
Steven
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." - Jon Ronson
More information about the Python-list
mailing list