simpler increment of time values?

Ian Kelly ian.g.kelly at gmail.com
Thu Jul 5 13:06:41 EDT 2012


On Thu, Jul 5, 2012 at 7:56 AM, Chris Angelico <rosuav at gmail.com> wrote:
> I'm not familiar with the Python classes (I tend to think in terms of
> language-agnostic algorithms first, and specific libraries/modules/etc
> second), but if you're working with simple integer seconds, your
> datelessness is just modulo arithmetic.
>
> time1 + time2  --> (time1 + time2) % 86400
> time1 - time2  --> (time1 + 86400 - time2) % 86400

The "+ 86400" is redundant; you'll get the same answer with or without
it.  There is nothing to fear from going negative when doing modulo
arithmetic, because unlike C, Python actually has well-defined
semantics regarding modulo division of negative numbers.

>>> (13382 + 86400 - 42597) % 86400
57185
>>> (13382 - 42597) % 86400
57185

Cheers,
Ian



More information about the Python-list mailing list