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

Luke picture Luke · May 14, 2009 · Viewed 15.1k times · Source

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

Answer

sth picture sth · May 14, 2009

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)