user776942
user776942

Reputation:

why is my timedelta math off?

I couldn't find anything online and probably has some stupid simple answer, but being new to python I don't understand:

import pytz
from datetime import datetime, timedelta

now_utc = pytz.utc.localize(datetime.utcnow())
past = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=120))
delta = (now_utc-past).seconds
print delta # prints '119', not '120'

Why does it always print 1 second less than the timedelta I specify? If I change "seconds=120" to "minutes=1", I get '59', not '60'. Why?

Upvotes: 2

Views: 188

Answers (1)

Fedor Gogolev
Fedor Gogolev

Reputation: 10561

>>> print now_utc - past
0:01:59.999976

So there is 119 seconds and 999976 microseconds. Because you did two separate datetime.utcnow() calls with a little (24 microseconds) interval.

Upvotes: 8

Related Questions