Python difference in datetime is now versus datetime now

I got into a problem or, if possible, I will add a turn! Not sure interesting! In python datetime library to get time difference, like in the following 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 it datetime.datetime.now() - datetime.datetime.now()outputs as -1 days, 86399 seconds , while assigning the current time to a variable and a computational difference gives the desired result 0 days, 4 seconds .

The results seem a bit confusing, it would be helpful if someone could decrypt what goes after

Note. I am using Python 2.7

+4
source share
2 answers

timedelta

, OverflowError .

, . :

>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)

python 2.7 3. both.

:

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)

:

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

, ( )

+4

" ".

>>> import datetime

>>> now0 = datetime.datetime.now()
>>> now0
datetime.datetime(2018, 2, 20, 12, 23, 23, 1000)
>>> delta = datetime.timedelta(microseconds=1)
>>> now1 = now0 + delta
>>> now0 - now1
datetime.timedelta(-1, 86399, 999999)

  • now0 1 st datetime.datetime.now()
  • , 2 nddatetime.datetime.now() ( delta, , , , , ). now1
  • ( -delta), now0 , now1 ( [ Python]: timedelta Objects )
+2

Source: https://habr.com/ru/post/1693863/


All Articles