putting date strings in order

MRAB google at mrabarnett.plus.com
Tue May 12 08:53:50 EDT 2009


noydb 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???

Sort the list, passing a function as the 'key' argument. The function
should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
you want to have a different start month then add the appropriate
integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
to make it wrap around (there are only 12 months in a year), returning
the result.



More information about the Python-list mailing list