I understand that seconds and microseconds are probably represented separately in datetime.timedelta
for efficiency reasons, but I just wrote this simple function:
def to_seconds_float(timedelta):
"""Calculate floating point representation of combined
seconds/microseconds attributes in :param:`timedelta`.
:raise ValueError: If :param:`timedelta.days` is truthy.
>>> to_seconds_float(datetime.timedelta(seconds=1, milliseconds=500))
1.5
>>> too_big = datetime.timedelta(days=1, seconds=12)
>>> to_seconds_float(too_big) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('Must not have days', datetime.timedelta(1, 12))
"""
if timedelta.days:
raise ValueError('Must not have days', timedelta)
return timedelta.seconds + timedelta.microseconds / 1E6
This is useful for things like passing a value to time.sleep
or select.select
. Why isn't something like this part of the datetime.timedelta
interface? I may be missing some corner case. Time representation seems to have so many non-obvious corner cases...
I rejected days right out to have a reasonable shot at some precision (I'm too lazy to actually work out the math ATM, so this seems like a reasonable compromise ;-).