Search code examples
djangodatetimedjango-timezone

Django timezone same day diff is not 0


test function

from django.utils import timezone

def date_diff_now(date):
    print(date)
    print(timezone.now())
    print(date - timezone.now())
    print((date - timezone.now()).days)

Result

2018-02-07 17:46:36.442314+00:00
2018-02-07 17:47:32.084900+00:00
-1 day, 23:59:04.357374
-1

Why the difference between 2 datetime on the same day does not return 0 ?


Solution

  • From Basic time and dates

    If the normalized value of days lies outside the indicated range, OverflowError is raised.

    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)
    

    So it looks like a known overflow error.