[英]TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.timedelta'
Python datetime
does not allow subtracting timedelta
from time
; Python
datetime
不允许从time
中减去timedelta
; I suppose that's because timedelta
can span over days and time
is only within 24 hrs (hh:mm:ss.ns).我想这是因为
timedelta
可以跨越数天,而time
仅在 24 小时内(hh:mm:ss.ns)。
Now the question is if there is a data structure similar to timedelta
that allows subtraction directly from time
?现在的问题是,是否有类似于
timedelta
的数据结构允许直接从time
中减法?
I understand that I can convert my datetime.time
to datetime.timedelta
to enable subtraction from another datetime.timedelta
.我知道我可以将我的
datetime.time
转换为datetime.timedelta
以启用另一个datetime.timedelta
的减法。 BUT I'm trying to avoid casting time
to timedelta
because I'm reading times from a large file and it's expensive to cast every time to timedelta.但是我试图避免将
time
转换为timedelta
,因为我正在从一个大文件中读取时间,并且每次转换为 timedelta 的成本都很高。 However, it is a one time operation to simply replace timedelta
with some_datastructure
(if that sth exist) and subtract directly from time
.但是,将
timedelta
简单地替换为some_datastructure
(如果存在)并直接从time
中减去是一次性操作。
example:例子:
t1 = datetime.time(hour=1, minute=1, second=1)
# t1 = datetime.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second)
t_diff = datetime.timedelta(hours=0, minutes=0, seconds=1)
print(t1-t_diff)
**ps how many time s did I use the word time ?! **ps 我用了多少次时间这个词?!
a conversion to datetime.datetime
instead of datetime.timedelta
would be more efficient:转换为
datetime.datetime
而不是datetime.timedelta
会更有效:
from random import randrange
from datetime import datetime, time, timedelta
# some random times:
N = int(1e6)
ts = [time(randrange(23),randrange(59),randrange(59),randrange(999999)) for _ in range(N)]
# to timedelta could look like
td = [timedelta(0, 0, (t.hour*60*60*1e6+t.minute*60*1e6+t.second*1e6+t.microsecond)) for t in ts]
# %timeit [timedelta(0, 0, (t.hour*60*60*1e6+t.minute*60*1e6+t.second*1e6+t.microsecond)) for t in ts]
# 856 ms ± 903 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
# to datetime could look like
today = datetime.now().date()
dt = [datetime.combine(today, t) for t in ts]
# %timeit [datetime.combine(today, t) for t in ts]
# 201 ms ± 1.85 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# now you'd do something with dt
ts_new = [(d + timedelta(seconds=5)).time() for d in dt]
# %timeit [(d + timedelta(seconds=5)).time() for d in dt]
# 586 ms ± 1.68 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
But still - for the 1M element example, the timeits show that we're definitely falling into the critical >1ms
range.但仍然 - 对于 1M 元素示例,时间表明我们肯定落入了
>1ms
的临界范围。 If you want to go faster, I guess you'll have to use another time format in the first place, such as for example integer (micro)seconds since midnight.如果你想 go 更快,我想你必须首先使用另一种时间格式,例如 integer (微)秒自午夜以来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.