开发者

Missing datetime.time.__sub__?

Why can't subtract two time objects? For exampl开发者_StackOverflowe, 12:00 - 11:00 = 1:00


from datetime import time
time(12,00) - time(11,00) # -> timedelta(hours=1)

It seems that datetime.time.__sub__ is missing

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

do you know why?


The time objects have no date, so for example, the 12:00 might be (say) on a Wed and the 11:00 on the preceding Tue, making the difference 25 hours, not one (any multiple of 24 might be added or subtracted). If you know they're actually on the same date, just apply any arbitrary date to each of them (making two datetime objects) and then you'll be able to subtract them. E.g.:

import datetime

def timediff(t1, t2):
  td = datetime.date.today()
  return datetime.datetime.combine(td, t1) - datetime.datetime.combine(td, t2)


You can get your desired result by

t1 = time(12, 0)
t2 = time(11, 0)
td = timedelta(hours=t1.hour-t2.hour, minutes=t1.minute-t2.minute)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜