25

我希望能够做到以下几点:

num_intervals = (cur_date - previous_date) / interval_length

或者

print (datetime.now() - (datetime.now() - timedelta(days=5))) 
      / timedelta(hours=12)
# won't run, would like it to print '10'

但时间增量不支持除法运算。有没有办法可以为 timedeltas 实现除法?

编辑:看起来这已添加到 Python 3.2(感谢 rincewind!):http ://bugs.python.org/issue2706

4

3 回答 3

14

整数除法和乘法似乎开箱即用

>>> from datetime import timedelta
>>> timedelta(hours=6)
datetime.timedelta(0, 21600)
>>> timedelta(hours=6) / 2
datetime.timedelta(0, 10800)
于 2009-05-14T20:44:46.130 回答
11

当然,只需转换为秒数(分钟、毫秒、小时,选择单位)并进行除法。

编辑(再次):所以你不能分配给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

于 2009-05-14T20:41:21.850 回答
4

您可以像这样覆盖除法运算符:

class MyTimeDelta(timedelta):
     def __div__(self, value):
          # Dome something about the object
于 2009-05-14T20:41:59.727 回答