classification
Title: incorrect timedelta yielded by two on-the-fly nows subtraction
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.1, Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mark.dickinson, mykhal
Priority: normal Keywords:

Created on 2010-05-07 11:11 by mykhal, last changed 2010-05-07 12:15 by mark.dickinson. This issue is now closed.

Messages (4)
msg105190 - (view) Author: Michal Božoň (mykhal) Date: 2010-05-07 11:11
now() - now() from datetime.datetime produces not-nearly-zero timedelta:

>>> import datetime
>>> (datetime.datetime.now() - datetime.datetime.now()).seconds
86399

(i can't in the moment figure out why this is happening, sice the datetime library is written in C)
msg105192 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2010-05-07 11:33
This is correct behaviour.  Note that .seconds is only one of the three attributes that contribute to the value of a timedelta:  the others are .microseconds and .days.  A timedelta is normalised in such a way that td.seconds and td.microseconds are always nonnegative;  this means that td.days will be strictly negative for negative timedeltas.  In your case the timedelta will have a .days attribute of -1, and the total time represented (e.g., in seconds, 86400.0 * td.days + td.seconds + 0.000001 * td.microseconds) will be small and negative.

Here's what I get on my system (in the py3k branch):

Python 3.2a0 (py3k:80840:80842, May  7 2010, 12:29:35) 
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> td = datetime.datetime.now() - datetime.datetime.now()
>>> td.microseconds, td.seconds, td.days
(998977, 86399, -1)
>>> print(td)
-1 day, 23:59:59.998977
>>> 1e-6 * td.microseconds + td.seconds + 86400 * td.days
-0.0010230000043520704
>>> td.total_seconds() # new in Python 2.7, 3.2
-0.0010230000043520704
msg105194 - (view) Author: Michal Božoň (mykhal) Date: 2010-05-07 11:58
ok, my fault, i should have tried

>>> (abs(datetime.datetime.now() - datetime.datetime.now())).seconds
0

sorry :)
msg105196 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2010-05-07 12:15
Hmm.  My example did make me realize that the total_seconds() method isn't as accurate as it could be.  I'll open another issue for this.
History
Date User Action Args
2010-05-07 12:15:43mark.dickinsonsetmessages: + msg105196
2010-05-07 11:58:51mykhalsetmessages: + msg105194
2010-05-07 11:33:24mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg105192

resolution: not a bug
2010-05-07 11:20:35mykhalsettitle: incorrect timedelta yielded by two on-the-fly nows -> incorrect timedelta yielded by two on-the-fly nows subtraction
2010-05-07 11:11:16mykhalcreate