如何在 python 中的 datetime.timedelta 上执行除法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/865618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:00:46  来源:igfitidea点击:

How can I perform divison on a datetime.timedelta in python?

pythondatedatetimedivisiontimedelta

提问by Luke

I'd like to be able to do the following:

我希望能够执行以下操作:

num_intervals = (cur_date - previous_date) / interval_length

or

或者

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

but the division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas?

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

Edit:Looks like this was added to Python 3.2 (thanks rincewind!): http://bugs.python.org/issue2706

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

采纳答案by David Z

Sure, just convert to a number of seconds (minutes, milliseconds, hours, take your pick of units) and do the division.

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

EDIT(again): so you can't assign to timedelta.__div__. Try this, then:

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

And to incorporate this into nadia's suggestion:

并将其纳入 nadia 的建议中:

class MyTimeDelta:
    __div__ = divtd

Example usage:

用法示例:

>>> 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

etc. Of course you could even name (or alias) your custom class timedeltaso it gets used in place of the real timedelta, at least in your code.

等等。当然你甚至可以命名(或别名)你的自定义类,timedelta这样它就可以代替真正的timedelta,至少在你的代码中。

回答by sth

Division and multiplication by integers seems to work out of the box:

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

>>> from datetime import timedelta
>>> timedelta(hours=6)
datetime.timedelta(0, 21600)
>>> timedelta(hours=6) / 2
datetime.timedelta(0, 10800)

回答by Nadia Alramli

You can override the division operator like this:

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

class MyTimeDelta(timedelta):
     def __div__(self, value):
          # Dome something about the object