简体   繁体   中英

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

I have two datetime.time objects in Python, eg,

>>> 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 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, ie, in this case it should be 1100000. Any ideas?

The class datetime.time does not support object subtraction for the same reason it doesn't support object comparison, ie because its objects might not define their tzinfo attribute:

comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.

You should use datetime.datetime which include both the date and the time.

If the two times refers to a single day, you can tell python that the date is today, with date.today() and combine the date with the time using datetime.combine .

Now that you have datetimes you can perform subtraction, this will return a datetime.timedelta instance, which the method total_seconds() that will return the number of seconds (it's a float that includes the microseconds information). So multiply by 10 6 and you get the microseconds.

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

You can also just use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM