dateutil.relativedelta - How to get duration in days?

故事扮演 提交于 2019-12-05 00:56:54

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

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!