Rob Bednark
Rob Bednark

Reputation: 28122

How to convert dateutil.relativedelta object to datetime.timedelta object?

How can I convert a dateutil.relativedelta object to a datetime.timedelta object?

e.g.,

# pip install python-dateutil

from dateutil.relativedelta import relativedelta
from datetime import timedelta

rel_delta = relativedelta(months=-2)
# How can I convert rel_delta to a timedelta object so that I can call total_seconds() ?
time_delta = ???(rel_delta)  
time_delta.total_seconds()  # call the timedelta.total_seconds() method

Upvotes: 4

Views: 11645

Answers (3)

Ben
Ben

Reputation: 2547

In case someone is looking to convert a relativedelta to a timedelta from a specific date, simply add and subtract the known time:

utcnow = datetime.utcnow()
rel_delta = relativedelta(months=-2)
time_delta = utcnow + rel_delta - utcnow  # e.g, datetime.timedelta(days=-62)

As a commenter points out, the resulting timedelta value will differ based on what month it is.

Upvotes: 6

Craig Finch
Craig Finch

Reputation: 1008

Depending on why you want to call total_seconds, it may be possible to refactor your code to avoid the conversion altogether. For example, consider a check on whether or not a user is over 18 years old:

datetime.date.today() - user['dateOfBirth'] < datetime.timedelta(days=365*18)

This check is not a good idea, because the timedelta object does not account for things like leap years. It's tempting to rewrite as:

datetime.date.today() - user['dateOfBirth'] < dateutil.relativedelta.relativedelta(years=18)

which would require comparing a timedelta (LHS) to a relativedelta (RHS), or converting one to the other. However, you can refactor the check to avoid this conversion altogether:

user['dateOfBirth'] + dateutil.relativedelta.relativedelta(years=18) > datetime.date.today()

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

You can't, for one huge reason: They don't store the same information. datetime.timedelta only stores days, seconds, and milliseconds, whereas dateutil.relativedelta stores every single time component fed to it.

That dateutil.relativedelta does so is important for storing things such as a difference of 1 month, but since the length of a month can vary this means that there is no way at all to express the same thing in datetime.timedelta.

Upvotes: 9

Related Questions