Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 754
Luke Avatar asked May 14 '09 20:05

Luke


People also ask

How do you subtract Timedelta in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.

What is Timedelta in datetime Python?

A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

What is the use of Timedelta () function in Python?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.


2 Answers

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) 
like image 102
sth Avatar answered Sep 30 '22 18:09

sth


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.

like image 36
David Z Avatar answered Sep 30 '22 20:09

David Z