putting date strings in order

Jaime Fernandez del Rio jaime.frio at gmail.com
Tue May 12 14:38:57 CEST 2009


If you simply want to generate an ordered list of months, start with
it in order:

    dates = ["x_jan",...,"x_dec"]

and if the desired starting month is

    start = 6 # i.e. x_jun

    dates = dates[start - 1:] + dates[:start - 1]

If you have to sort the list itself, I would use an intermediate
dictionary to hold the positions, as in:

    months = {"x_jan" : 1, ..., "x_dec" : 12}

You can then sort the list with :

    dates.sort(None,lambda x : months[x])

and then do the

    dates = dates[start - 1:] + dates[:start - 1]

or alternatively you can get the sorting directly as you want it with:

    dates.sort(None,lambda x : (months[x] - start + 1) % 12)


Jaime



On Tue, May 12, 2009 at 1:58 PM, noydb <jenn.duerr at gmail.com> wrote:
> On May 11, 11:30 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>> noydb <jenn.du... at gmail.com> writes:
>> > Anyone have any good ideas?  I was curious to see what people came up
>> > with.
>>
>> Is this a homework assignment?  Some hints:
>>
>> 1) figure out how to compare two month names for chronological order,
>>    leaving out the issue of the starting month not being january.
>> 2) figure out how to adjust for the starting month.  The exact
>>    semantics of the "%" operator might help do this concisely.
>
> Ha!  No, this is not a homework assignment.  I just find myself to be
> not the most eloquent and efficient scripter and wanted to see how
> others would approach it.
>
> I'm not sure how I follow your suggestion.  I have not worked with the
> %.  Can you provide a snippet of your idea in code form?
>
> I thought about assigning a number string (like 'x_1') to any string
> containing 'jan' -- so x_jan would become x_1, and so on.  Then I
> could loop through with a counter on the position of the number (which
> is something i will need to do, comparing one month to the next
> chronological month, then that next month to its next month, and so
> on).  And as for the starting postion, the user could declare, ie, aug
> the start month.  aug is position 8.  therefore subtract 7 from each
> value, thus aug becomes 1.... but then I guess early months would have
> to be add 5, such that july would become 12.  Ugh, seems sloppy to me.
>
> Something like that....   seems poor to me.  Anybody have a bteer
> idea, existing code???
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.



More information about the Python-list mailing list