On 12/13/2011 06:46 AM, rail shafigulin wrote:
i found something interesting during the timedate difference calculation

import datetime
import time

def main():
   mydatetime = datetime.datetime.now()
   time.sleep(1)
   mydatetime2 = datetime.datetime.now()
   diff = mydatetime - mydatetime2

   print(diff)

if __name__ == '__main__':
   main()

if you run this code the result you get will be
-1 day, 23:59:59

at least that is what i'm getting.

i was expecting to get -1 second. diff object is of type timedelta. this
kind of objects represent duration, at least that is what i understood
from the documentation
(http://docs.python.org/release/3.1.3/library/datetime.html#timedelta-objects).
so, is this a bug in the timedelta implementation or is it me not
understanding documentation properly?

It's due to timedelta normalization; in timedelta object only the day part is ever negative, you never had negative hour, minute, or second. The `-1 day, 23:59:59` means to subtract 1 day, then add 23:59:59; therefore giving us -1 second.

It is documented behavior, although perhaps hinted too subtly, from the docs:

"""
Note that normalization of negative values may be surprising at first. For example,

>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
"""

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to