Converting a timedelta to a float

The problem

You need to convert a time difference into a floating point quantity, like 2.5 days. Or you may want to do something related like round a fdatetime difference up or down, e.g. 3 or 2 days for our previous example.

The complications

When you subtract a datetime from another in Python, you get a timedelta object:

> from datetime import datetime, timedelta
> d1 = datetime (year=2015, month=6, day=1, hour=12, minute=30)
> d2 = datetime (year=2015, month=6, day=7, hour=18, minute=15)
> td = d2 - d1
> td
datetime.timedelta(6, 20700)
> type (td)
datetime.timedelta

Unfortunately, timedelta only returns the "parts" that make it up - days, seconds and microseconds:

> td.days, td.seconds, td.microseconds
(6, 20700, 0)

The solution

In Python 3, you can divide one timedelta by another, which lets you do this:

> td / timedelta (days=1)

but not in Python 2.

However, timedelta has a method totalseconds, which returns the whole delta expressed as decimal seconds:

> td.total_seconds()
539100.0
> timedelta (days=1, microseconds=20).total_seconds()
86400.00002

Which lets us take the above solution and do this to work out the fractional days:

> td.total_seconds() / timedelta (days=1).total_seconds()
6.239583333333333

Unresolved issues

If you to express a time difference as microseconds, minutes, hours etc. you're going to have to do some more math.