How do you get the difference between two time objects in Python

I have two datetime.time objects in Python, for example,

>>> x = datetime.time(9,30,30,0)
>>> y = datetime.time(9,30,31,100000)

However, when I do (yx) as what I would do for the datetime.datetime object, I got the following error:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y-x
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I need to get the yx value in microseconds, i.e. in this case it should be 1,100,000. Any ideas?

+4
source share
1 answer

The class datetime.timedoes not support subtraction of objects for the same reason that it does not support comparison of objects, i.e. because its objects may not be define an attribute tzinfo:

, a b, a b . , , TypeError . tzinfo, tzinfo . tzinfo, UTC ( self.utcoffset()). , , TypeError , == ! =. False True.

datetime.datetime, , .

, python, , date.today() datetime.combine.

, , datetime.timedelta, total_seconds(), ( float, ). 10 6 .

from datetime import datetime, date, time

x = time(9, 30, 30, 0)
y = time(9, 30, 31, 100000)

diff = datetime.combine(date.today(), y) - datetime.combine(date.today(), x)
print diff.total_seconds() * (10 ** 6)        # 1100000.0

timedeltas:

from datetime import timedelta
x = timedelta(hours=9, minutes=30, seconds=30)
y = timedelta(hours=9, minutes=30, seconds=31, microseconds=100000)
print (y - x).total_seconds() * (10 ** 6)     # 1100000.0
+7

All Articles