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
.
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()),
microseconds=tdelta.microseconds)
>>> to_relativedelta(timedelta(seconds=0.3))
relativedelta(microseconds=+300000)
>>> to_relativedelta(timedelta(seconds=3))
relativedelta(seconds=+3)
>>> to_relativedelta(timedelta(seconds=300))
relativedelta(minutes=+5)
>>> to_relativedelta(timedelta(seconds=3000000))
relativedelta(days=+34, hours=+17, minutes=+20)
d = datetime.timedelta(...)
dateutil.relativedelta.relativedelta(seconds=d.total_seconds())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With