python timedelta后一个月,如何在python中对datetime.timedelta执行除法?

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?

Edit: 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 (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

And to incorporate this into nadia's suggestion:

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 timedelta so it gets used in place of the real timedelta, at least in your code.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值