putting date strings in order

John Machin sjmachin at lexicon.net
Tue May 12 11:57:37 EDT 2009


On May 13, 1:02 am, MRAB <goo... at mrabarnett.plus.com> wrote:
> John Machin wrote:
> > MRAB <google <at> mrabarnett.plus.com> writes:
> >> 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
>
> > and if you don't like what that produces, try subtract :-)
>
> Oops!
>
> >> 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.
>
> Actually, subtract the start month, add 12, and then modulo 12.

Ummm ... 12 modulo 12 is a big fat zero, and Python's % is a genuine
modulo operator; unlike that of K&R C, it's defined not to go wobbly
on negatives.

| >>> [(i - 8 + 12) % 12 for i in range(12)]
| [4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3]

| >>> [(i - 8     ) % 12 for i in range(12)]
| [4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3]



More information about the Python-list mailing list