Get min and max dates

Peter Heitzer peter.heitzer at rz.uni-regensburg.de
Thu Dec 8 04:23:49 EST 2016


DFS <nospam at dfs.com> 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:
>========================================================================
>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))

>print 'min: ' + min(dts2)[1]
>print 'max: ' + max(dts2)[1]
>========================================================================
>$python getminmax.py
>min: 20-Aug-1997
>max: 07-Nov-2014

>which is correct, but I sense a more pythonic way, or a one-liner list 
>comprehension, is in there somewhere.
I'd use strptime from the time module.

Then you could write
dts2.append(strptime(d,'%d-%b-%Y)
min and max return a struct_time type that can easily converted to
the original date format

-- 
Dipl.-Inform(FH) Peter Heitzer, peter.heitzer at rz.uni-regensburg.de


More information about the Python-list mailing list