dateutil.relativedelta - How to get duration in days?

Emanuel Saringan picture Emanuel Saringan · Jan 12, 2015 · Viewed 10.5k times · Source

I wish to get the total duration of a relativedelta in terms of days.

Expected:

dateutil.timedelta(1 month, 24 days) -> dateutil.timedelta(55 days)

What I tried:

dateutil.timedelta(1 month, 24 days).days -> 24 (WRONG)

Is there a simple way to do this? Thanks!

Answer

Marcel Wilson picture Marcel Wilson · Apr 20, 2017

This one bothered me as well. There isn't a very clean way to get the span of time in a particular unit. This is partly because of the date-range dependency on units.

relativedelta() takes an argument for months. But when you think about how long a month is, the answer is "it depends". With that said, it's technically impossible to convert a relativedelta() directly to days, without knowing which days the delta lands on.

Here is what I ended up doing.

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

rd = relativedelta(years=3, months=7, days=19)
# I use 'now', but you may want to adjust your start and end range to a specific set of dates.
now = datetime.now()

# calculate the date difference from the relativedelta span
then = now - rd
# unlike normal timedelta 'then' is returned as a datetime
# subtracting two dates will give you a timedelta which contains the value you're looking for
diff = now - then

print diff.days