Search code examples
pythonpython-dateutilrelativedelta

Why does relativedelta with positive arguments return a date in the past?


I have some trouble to understand the behavior of dateutil.relativedelta. I understand that relativedelta could return past dates if I use negative arguments as specified in relativedelta doc.

However, when I provide positive parameters, I expect that it always return a date in the future... that seems legit right?

My use case is the following : we are Tuesday, it is 8:35. I want to get the date of the closest Monday and Tuesday at 6:00.

Here what I did. The first result seems correct to me, while the second one is wrong.

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2016, 11, 29, 8, 35, 23, 786349)

>>> from dateutil import relativedelta
>>> now.weekday()
1

>>> now + relativedelta.relativedelta(weekday=0, hour=6, minute=0) # should give a time in the future
datetime.datetime(2016, 12, 5, 6, 0, 23, 786349)  # here this is correct, in the future

>>> now + relativedelta.relativedelta(weekday=1, hour=6, minute=0) # should give a time in the future
datetime.datetime(2016, 11, 29, 6, 0, 23, 786349)  # but this is in the past / I would expect result (2016, 12, 6, 6, 0, 23, 786349)

So , am I doing something wrong here ?


Solution

  • I think it's in the doc:

    Starting with, about weekday:

    These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1.

    So by passing 1, it's like you're passing (1, 1)

    Then, continuing on the doc, on the 7th dot of behavior of operations with relativedelta:

    Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won’t change the day.

    So the 29th of November is already a Tuesday, and you're asking for a Tuesday.

    So nothing changes.