Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two datetime.time objects in Python, e.g.,

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

However, when I do (y-x) 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 y-x value in microseconds, i.e., in this case it should be 1100000. Any ideas?

like image 483
Mariska Avatar asked Aug 12 '14 13:08

Mariska


1 Answers

The class datetime.time does not support object subtraction for the same reason it doesn't support object comparison, i.e. 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 106 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
like image 124
enrico.bacis Avatar answered Sep 23 '22 21:09

enrico.bacis