Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to convert python datetime.timedelta to dateutil.relativedelta

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.

like image 535
Williams Avatar asked Jun 07 '13 06:06

Williams


2 Answers

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)
like image 178
Petr Viktorin Avatar answered Oct 31 '22 14:10

Petr Viktorin


d = datetime.timedelta(...)
dateutil.relativedelta.relativedelta(seconds=d.total_seconds())
like image 30
falsetru Avatar answered Oct 31 '22 14:10

falsetru