如何在python中对datetime.timedelta执行除法? [英] How can I perform divison on a datetime.timedelta in python?

查看:545
本文介绍了如何在python中对datetime.timedelta执行除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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'

但timedelta不支持除法运算。有没有一种方法可以实现timedelta的除法?

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

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

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

推荐答案

当然,只需将其转换为秒(分钟,毫秒,小时,请选择单位)并进行除法即可。

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

EDIT (再次):这样您就无法分配给 timedelta .__ div __ 。试试这个,然后:

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

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的建议:

And to incorporate this into nadia's suggestion:

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 命名(或别名),以便使用它代替真正的 timedelta ,至少在您的代码中。

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

这篇关于如何在python中对datetime.timedelta执行除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆