Search code examples
pythondatetimepytz

datetime.now() - date.now() is returning -1 days


datetime is giving very spooky results:

In:

tz = pytz.timezone('America/New_York') 
d1 = datetime.now(tz)

d2 = datetime.now(tz) + timedelta(seconds=0)

delta = d1-d2

print(delta, delta.seconds, delta.total_seconds(), sep="\n")

Out:

-1 day, 23:59:59.999930
86399
-7e-05

I have tried with and without timezones, with and without timedelta(seconds = 0) and have gotten the same result.

When I do:

tz = pytz.timezone('America/New_York') 
d1 = datetime.now(tz)

d2 = d1 + timedelta(seconds=0)

delta = d1-d2

print(delta, delta.seconds, delta.total_seconds(), sep="\n")

I get 0 as expected. What have I done?!

I am importing as follows (if this could be the issue):

from datetime import datetime, timedelta
import pytz

I was reading the delta print out wrong, I didn't realize it was -1 day + 23:59. Oops..


Solution

  • You're calling datetime.now() twice. Of course some amount of time passed between those two calls.

    Your delta calculation is backwards. It should be:

    delta = d2-d1