Take the 2-minute tour ×

Is there an elegant was to convert between relativedelta and timedelta?

The use case is getting user input ISO date. Python's isodate will return either isodate.duration.Duration or datetime.timedelta.

We need the features of relativedelta (per What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days? -- it does more) so need to convert both these types to a relativedata.

share|improve this question

2 Answers 2

up vote 0 down vote accepted

Just take the total number of seconds and microseconds, that's all a timedelta object stores:

def to_relativedelta(tdelta):
    return relativedelta(seconds=int(tdelta.total_seconds()),

>>> to_relativedelta(timedelta(seconds=0.3))
>>> to_relativedelta(timedelta(seconds=3))
>>> to_relativedelta(timedelta(seconds=300))
>>> to_relativedelta(timedelta(seconds=3000000))
relativedelta(days=+34, hours=+17, minutes=+20)
share|improve this answer
The microseconds are included in the total_seconds. –  Lennart Regebro Jun 7 '13 at 7:19
@LennartRegebro: Yes, but relativedelta doesn't accept fractional seconds (relativedelta(seconds=0.3) gives relativedelta(seconds=+0)). Also, as the documentation states, microseconds may not be accurate for very large intervals. –  Petr Viktorin Jun 7 '13 at 7:26
relativedelta(seconds=0.3) gives relativedelta(seconds=0.3) to me. I'm using python-dateutil 1.5 –  falsetru Jun 7 '13 at 7:29
@falsetru, that's weird. It should at least normalize to relativedelta(microseconds=+300000). (I'm using version 1.5 on Python 2.7 and 2.0 on Python 3, on Linux.) –  Petr Viktorin Jun 7 '13 at 7:45
@petr-viktorin, My comment was wrong. I spelled "second" instead of "seconds". –  falsetru Jun 7 '13 at 7:59
d = datetime.timedelta(...)
share|improve this answer
docs.python.org/2/library/… –  falsetru Jun 7 '13 at 6:45

Your Answer


