当然,只需转换为秒数(分钟、毫秒、小时,选择单位)并进行除法。
编辑(再次):所以你不能分配给timedelta.__div__
. 试试这个,然后:
divtdi = datetime.timedelta.__div__
def divtd(td1, td2):
if isinstance(td2, (int, long)):
return divtdi(td1, td2)
us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days)
us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days)
return us1 / us2 # this does integer division, use float(us1) / us2 for fp division
并将其纳入 nadia 的建议:
class MyTimeDelta:
__div__ = divtd
示例用法:
>>> divtd(datetime.timedelta(hours = 12), datetime.timedelta(hours = 2))
6
>>> divtd(datetime.timedelta(hours = 12), 2)
datetime.timedelta(0, 21600)
>>> MyTimeDelta(hours = 12) / MyTimeDelta(hours = 2)
6
等等当然,您甚至可以命名(或别名)您的自定义类,以便至少在您的代码中timedelta
使用它来代替 real 。timedelta