19

I'm trying to divide one timedelta object with another to calculate a server uptime:

>>> import datetime
>>> installation_date=datetime.datetime(2010,8,01)
>>> down_time=datetime.timedelta(seconds=1400)
>>> server_life_period=datetime.datetime.now()-installation_date
>>> down_time_percentage=down_time/server_life_period
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'datetime.timedelta' 
           and 'datetime.timedelta'

I know this has been solved in Python 3.2, but is there a convenient way to handle it in prior versions of Python, apart from calculating the number of microseconds, seconds and days and dividing?

Thanks,

Adam

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • possible duplicate of [How can I perform divison on a datetime.timedelta in python?](http://stackoverflow.com/questions/865618/how-can-i-perform-divison-on-a-datetime-timedelta-in-python) – Mechanical snail Sep 13 '12 at 14:37

1 Answers1

34

In Python ≥2.7, there is a .total_seconds() method to compute the total seconds contained in the timedelta:

>>> down_time.total_seconds() / server_life_period.total_seconds()
0.0003779903727652387

Otherwise, there is no way but to compute the total microseconds (for versions < 2.7)

>>> def get_total_seconds(td): return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6
... 
>>> get_total_seconds(down_time) / get_total_seconds(server_life_period)
0.0003779903727652387
Engineer2021
  • 3,288
  • 6
  • 29
  • 51
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005