[Tutor] Need help with dates in Python

Francesco Loffredo fal at libero.it
Thu Mar 10 20:35:36 CET 2011


On 09/03/2011 9.21, nookasree ponamala wrote:
> Hi,
>
> I need help in finding the minimum date and maximum date in a file.
> Here is my test file:
> s.no:	dt1	amt	id1	id2
> 452     2010-02-20      $23.26      059542        06107
> 452     2010-02-05      $20.78      059542        06107
> 451     2010-02-24      $5.99       059542        20151
> 452     2010-02-12      $114.25     839745        98101
> 452     2010-02-06      $28.00      839745        06032
> 451     2010-02-12      $57.00      839745        06269
>
> I want to get the minimum and maximum dt1 for each id1
>
> Required result:
>
> id1 mindate maxdate
> 059542	2010-02-24	2010-02-20		
> 839745	2010-02-06	2010-02-12
>
> Code: The code I tried. It doesn't work though.

I noticed that your dates are formatted in a way that makes it easy to compare them as strings.
This allows you not only to do without splitting dates into year, month and day, but also to do without the datetime module:
I'm also, AFAIK, the first one to address your need for the min and max date FOR EACH ID1, not in the whole file.

.    ids = {}  # create an empty dictionary to store results
.    for L in open("test.txt", "r"):
.      S = L.split()  # allow direct access to fields
.      if S[3] in ids:
.        mindate, maxdate = ids[S[3]]  # current stored minimum and maximum date
.        if S[1] < mindate:
.          mindate = S[1]
.        if S[1] > maxdate:
.          maxdate = S[1]
.        ids[S[3]] = (mindate, maxdate)  # new stored min and max
.      else:
.        ids[S[3]] = (S[1], S[1])  # initialize storage for the current id1, with min and max in a tuple
.    #leave print formatting as an exercise to the reader (but you can do without it!)
.    print ids

Hope this helps...
Francesco


-----
Nessun virus nel messaggio.
Controllato da AVG - www.avg.com
Versione: 10.0.1204 / Database dei virus: 1497/3495 -  Data di rilascio: 09/03/2011



More information about the Tutor mailing list