How do you get the difference between two time objects in Python
我在Python中有两个datetime.time对象,例如,
1 2 | >>> x = datetime.time(9,30,30,0) >>> y = datetime.time(9,30,31,100000) |
但是,当我像对datetime.datetime对象那样做(y-x)时,我收到以下错误:
1 2 3 4 | 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' |
我需要以微秒为单位得到y-x值,即在这种情况下它应该是1100000.任何想法?
类
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.
您应该使用
如果两次引用一天,您可以告诉python日期是今天,使用
既然你有日期时间你可以执行减法,这将返回一个datetime.timedelta实例,方法
1 2 3 4 5 6 7 | 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:
1 2 3 4 | 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 |