Search code examples
pythondatetimediff

Python difference in datetime now against datetime now


I have got into an issue or might quite possibly feature in turn! Not sure, wondering!! In python's datetime library, to get difference in time, as in below snippet.

>>> import datetime
>>> datetime.datetime.now() - datetime.datetime.now()
datetime.timedelta(-1, 86399, 999958)
>>> tnow = datetime.datetime.now()
>>> datetime.datetime.now() - tnow
datetime.timedelta(0, 4, 327859)

I would like to understand why datetime.datetime.now() - datetime.datetime.now() is producing output as -1 days, 86399 seconds whereas assigning current time to some variable and computing difference gives desired output 0 days, 4 seconds.

The results seems to be bit confusing, it would be helpful if someone could decode whats going behind

Note: I'm using Python 2.7


Solution

  • From the documentation for timedelta objects:

    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)
    

    This occurs in both Python 2.7 and Python 3.

    The reason for the observed result is simple:

    a , b = datetime.datetime.now(), datetime.datetime.now()
    # here datetime.now() in a will be <= b.
    # That is because they will be executed separately at different CPU clock cycle.
    
    a - b
    # datetime.timedelta(-1, 86399, 999973)
    
    b - a
    # datetime.timedelta(0, 0, 27)
    

    To get the proper time difference:

    (tnow - datetime.datetime.now()).total_seconds()
    # output: -1.751166
    

    See also Python timedelta issue with negative values.