15

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!

  • dateutil does not have `relativedelta` nor `timedelta` at least not the version Im using as such I dont understand your question `datetime.timedelta` does have a `.days` property ... – Joran Beasley Jan 12 '15 at 18:06
  • I'm using this https://labix.org/python-dateutil. `.days` will just return the number of days excluding the months (see my example). –  Jan 12 '15 at 18:08
  • It seems unlikely that one would be able to extract total time in days from a timedelta as different months and years have different numbers of days. Ie. the number of days depends on the relative month and year (information not available to the timedelta). – Alex Jan 12 '15 at 18:31

3 Answers3

16

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
Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55
5

Simple date diff does it actually.

    >>> from datetime import datetime
    >>> (datetime(2017, 12, 1) - datetime(2018, 1, 1)).days
    -31

To get positive number You can swap dates or use abs:

    >>> abs((datetime(2017, 12, 1) - datetime(2018, 1, 1)).days)
    31
egvo
  • 1,493
  • 18
  • 26
-1

In many situations you have a much restricted relativedelta, in my case, my relativedelta had only relative fields set (years, months, weeks, and days) and no other field. You may be able to get away with the simple method.

This is definitely off by few days, but it may be all you need

(365 * duration.years) + (30 * duration.months) + (duration.days)

Manyu
  • 142
  • 8